reactjschart.jsreact-chartjschartjs-2.6.0react-chartjs-2

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


React Chartjs-2 : How can I implement the functionality where when a legend is clicked, instead of hiding the clicked legend, all other legends/datasets get hidden?


Solution

  • 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