简体   繁体   中英

React + Recharts legend not working properly

I am using React + Recharts to create a stacked and grouped bar chart, it is my first time using Recharts. but the legend is not working properly, I want the legend to toggle both graphs in each group, but it is only working for the left side bar and not for the right side bar. is it possible to make it work for both?

在此处输入图片说明

I did it like this:

const selectBar = event => {
  let updatedLabels = [];
  let updatedLabelsSpend = [];
  for (let i = 0; i < data.labels.length; i++) {
    let label = data.labels[i];
    let spendLabel = data.filteredDataSpend[i];

    if (label.key !== event.value) {
      updatedLabels.push(label);
      updatedLabelsSpend.push(spendLabel);
    } else {
      if (/\s/.test(label.key) && /\s/.test(spendLabel.key)) {
        let newLabel = { key: label.key.trim(), color: label.color };
        let newLabelSpend = {
          key: spendLabel.key.trim(),
          color: spendLabel.color,
        };
        updatedLabels.push(newLabel);
        updatedLabelsSpend.push(newLabelSpend);
      } else {
        let newLabel = { key: label.key + ' ', color: label.color };
        let newLabelSpend = {
          key: spendLabel.key + ' ',
          color: spendLabel.color,
        };
        updatedLabels.push(newLabel);
        updatedLabelsSpend.push(newLabelSpend);
      }
    }
  }
  setData({ ...data, labels: updatedLabels });
};

you can check the demo in demo

any help please?

You were missing the state update for filteredDataSpend , this little change fix it

    setData({
      ...data,
      labels: updatedLabels,
      filteredDataSpend: updatedLabelsSpend
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM