'Dynamically change type with react-chartjs-2 React

I'm using typescript in my project and I'm trying to change the type of chart, for example by button. And the official documentation of react-chartjs-2 declares the type as a const, so typescript doesn't compile it. What I should do and if it is really impossible?

My code:

const Stats = () => {
    const [type, setType] = useState('bar');

    const data = {
      labels,
      datasets: [
        {
            // in offical docs
            // type: 'bar' as const,
            type: type,
            label: 'Dataset 1',
            borderColor: 'rgb(255, 99, 132)',
            borderWidth: 2,
            fill: false,
            data: randomArray(),
        },
        {
            type: type,
            label: 'Dataset 2',
            backgroundColor: 'rgb(75, 192, 192)',
            data: randomArray(),
            borderColor: 'white',
            borderWidth: 2,
        },
        {
            type: type,
            label: 'Dataset 3',
            backgroundColor: 'rgb(53, 162, 235)',
            data: randomArray(),
        },
      ],
    };

    return (
        <div>
            <Chart type='bar' data={data} />
            <Button onClick={ () => setType('line')}>Change type</Button>
        </div>
    );
};


Solution 1:[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} />;
    }
  })()}
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aryan Gupta