0

I'm facing a scope problem with state within a react app.

I'm adding some buttons to my chart component at the top of high chart component.
Now, what I'd like is to add those buttons inside chart space (under title) to save some space.

The solution I found on older posts and forum was to use this method:

chart.events.render(this.renderer.button.add())

I'm not sure if this method is deprecated in favor of SVGRenderer.

My approach was

chart: {
    events: {
      render() {
        let chart = this;

        console.log("this chart", chart);
        const handlePeriodClick = (periodType) => {
          const filteredData = chart.options.data.map((option) =>({
            ...option,
            data: option.data.filter((item) =>
              moment(item[0]).diff(moment(item[0]).endOf(periodType), 'days') === 0)
          }));
          // need to acces states from React within Highchart.chart component
          this.setState({ filteredData });
        };

        chart.renderer.button('D',10, 55)
          .on('click', function () {
            handlePeriodClick('day');
          })
          .add();
        chart.renderer.button('W',35, 55)
          .on('click', function () {
            handlePeriodClick('week');
          })
          .add();
        chart.renderer.button('M',60, 55)
          .on('click', function () {
            handlePeriodClick('month');
          })
          .add();
      }
    }
  },

I need to update state inside that function call so as to reflect a data update. Here is a working demo.

I've also tried to use SVGRenderer instead of renderer but couldn't make it work.

Bernardo Marques
  • 925
  • 2
  • 10
  • 33

1 Answers1

1

A lot of happens in your demo and I don't understand clearly what do you want to achieve, but it seems that render callback is never triggered - this console.log("this chart", chart); don't show up.

Below are my advices on how to change state in the custom functions in the rendered buttons.

  1. Define the function and variable to attach this outside the scope.

Demo: https://codesandbox.io/s/highcharts-react-demo-1fm35?file=/demo.jsx

  1. If you want to only change the data you can do it also by using the series.update Highcharts feature - there will be no scope problem.

Demo: https://codesandbox.io/s/highcharts-react-demo-11mpt

Sebastian Wędzel
  • 11,417
  • 1
  • 6
  • 16
  • I forgot to call `Highcharts.setOptions(Highcharts.chart)` on my demo, that's why the console log wasn't being called (also all renderer block), I have just fixed that. Also, what is the `highcharts/highcharts-more` for? – Bernardo Marques Apr 29 '20 at 12:52
  • `highcharts-more` it is a module which extends basic Highcharts core. Some of the chart types requires it, like: https://api.highcharts.com/highcharts/series.columnpyramid – Sebastian Wędzel Apr 29 '20 at 12:58