martintt
Posts: 17
Joined: Tue Sep 25, 2018 12:29 pm

Dynamically changing chart type in React?

Hello again!

I'm fiddling with changing chart type on click in a React project and I can't get it to work properly.
It's basically something like this, where I try to push a new type with the update flag.
https://codesandbox.io/s/z28xnm1n43

And I'm not sure what's wrong here. It logs this.refs.highCharts as expected but I can't seem to update the type, getting an error (in this case, series is undefined) etc.

Any ideas?

(What I want to do is to have the bar switch between line and column upon button clicks).
rafalS
Posts: 2665
Joined: Thu Jun 14, 2018 11:40 am

Re: Dynamically changing chart type in React?

Hi, martintt!

Before I pass this topic to our React specialist, maybe this will be enough for you.
You can write your code in a chart.events.load event:

Code: Select all

chart: {
        events: {
          load: function() {
            let btn = document.getElementById("btn");
            let chart = this;
            btn.addEventListener("click", () => {
              chart.series[0].update({
                type: "line"
              });
            });
          }
        }
      },
Let me know if it's enough for you or I should forward this topic further.

codesandbox: https://codesandbox.io/s/km3z0nxp2v

Best regards!
Rafal Sebestjanski,
Highcharts Team Lead
martintt
Posts: 17
Joined: Tue Sep 25, 2018 12:29 pm

Re: Dynamically changing chart type in React?

rafalS wrote:Hi, martintt!

Before I pass this topic to our React specialist, maybe this will be enough for you.
You can write your code in a chart.events.load event:

Best regards!

Hmm, yes, that could work.
Current setup has another method for triggering the line/bar switch - and I'd like to just place the handler function inside that one (since it does a few other things at the same time).

So I somehow need to reference the chart options but don't know how...
martintt
Posts: 17
Joined: Tue Sep 25, 2018 12:29 pm

Re: Dynamically changing chart type in React?

Ok, sort of solved but still needs some tweaking input.
Again: https://codesandbox.io/s/z28xnm1n43

This way the sample works, but when I switch back to column (bar-button), it's like that specific serie is living on its own, not taking the other series in consideration. Do I need to redraw the chart somehow?

Funny thing is that in my project with this code it runs but the chart is not changing. I can see that it gets the "line" type but it still displays as column.
martintt
Posts: 17
Joined: Tue Sep 25, 2018 12:29 pm

Re: Dynamically changing chart type in React?

Ok, easy workaround. Toggling line/column with Reacts setState worked like a charm.
rafalS
Posts: 2665
Joined: Thu Jun 14, 2018 11:40 am

Re: Dynamically changing chart type in React?

Ok, I am glad you sorted it out!

Best regards
Rafal Sebestjanski,
Highcharts Team Lead

Return to “Highcharts Usage”