[Chartjs]-How to change React chartjs-2 legend click functionality to hide all except the one clicked?

1๐Ÿ‘

โœ…

By modifying the legend onClick function:

Options:

options: {
    plugins: {
        legend: {
            onClick: newLegendClickHandler
        }
    }
}

OnClick:

var newLegendClickHandler = function (e, legendItem, legend) {    
    let datasetIndex = legendItem.datasetIndex;
    let ci = legend.chart, metaSets = [];
    
    for (let i = 0; i < legend.chart.data.datasets.length; i++) {
        metaSets.push(ci.getDatasetMeta(i));
    }
    
    metaSets.forEach(function(meta) {
        meta.hidden = meta.index === datasetIndex ? false : true;
    });
    ci.update();
    
};

For more on this topic: Legend

A fiddle to see this in effect: JSFiddle

Edit:

Chartjs 2 does it almost the same way.

Options:

options: {
    legend: {
        onClick: newLegendClickHandler
    }
}

OnClick:

var newLegendClickHandler = function (e, legendItem) {    
    let datasetIndex = legendItem.datasetIndex;
    let ci = this.chart, metaSets = [];
    
    for (let i = 0; i < ci.data.datasets.length; i++) {
        metaSets.push(ci.getDatasetMeta(i));
    }
    
    metaSets.forEach(function(meta) {
        meta.hidden = meta.index === datasetIndex ? false : true;
    });
    ci.update();
};

Another Fiddle: 2.9.4 Fiddle

Edit 2:

If you are using chartjs 2.6.0 you need to change meta.index to meta.controller.index

Leave a comment