user17018145
user17018145

Reputation: 11

React-Chart.js legend onClick function

I'm working on a bar chart with multiple stacked datasets using the react wrapper for Chart.js(https://github.com/reactchartjs/react-chartjs-2).

I've been trying to make the chart show only one dataset at a time, but I'm having trouble coming up with the right function.

I want the chart to start off with all the datasets hidden(this part was easy) and when you click the legend I want the chart to only show only the selected dataset. So when you click one and then another I want the first one to get hidden.

I know I need to use the legend onClick option but I can't figure out how to set it up.

Any help would be appreciated, thanks!

Edit: Here is the chart in question: https://codesandbox.io/s/lucid-river-xhvtd?file=/src/charts/bar_chart.js

Upvotes: 0

Views: 3819

Answers (1)

LeeLenalee
LeeLenalee

Reputation: 31361

You can set all datasets to hide and then only the one clicked to show:

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'pink',
        hidden: true
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'orange',
        hidden: true
      },
      {
        label: '# of People',
        data: [3, 1, 15, 4, 9, 12],
        borderColor: 'cyan',
        hidden: true
      }
    ]
  },
  options: {
    plugins: {
      legend: {
        onClick: (evt, legendItem, legend) => {
          const index = legendItem.datasetIndex;
          const ci = legend.chart;

          legend.chart.data.datasets.forEach((d, i) => {
            ci.hide(i);
            d.hidden = true;
          })

          ci.show(index);
          legendItem.hidden = false;

          ci.update();
        }
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
</body>

Upvotes: 1

Related Questions