[Chartjs]-Dynamically change type with react-chartjs-2 React

3๐Ÿ‘

โœ…

You can do this, import ChartType from chart.js like

import {ChartType} from 'chart.js'

Then change the useState code to

const [type, setType] = useState<ChartType>('bar');

Now it should work

1๐Ÿ‘

You can use switch case

const [chartType, setChartType] = useState("Line");
...
...
return(

...

 {(() => {
    switch (chartType) {
      case "Line":
        return <Line data={gdata} options={goptions} />;
      case "Bar":
        return <Bar data={gdata} options={goptions} />;
      case "Pie":
        return <Pie data={gdata} options={goptions} />;
      case "Radar":
        return <Radar data={gdata} options={goptions} />;
      case "Scatter":
        return <Scatter data={gdata} options={goptions} />;

      default:
        return <Line data={gdata} options={goptions} />;
    }
  })()}
)

Leave a comment