3

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>
    );
};
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
SPR1NG
  • 174
  • 1
  • 11

2 Answers2

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

Vishnu Sajeev
  • 941
  • 5
  • 11
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} />;
    }
  })()}
)
Aryan Gupta
  • 131
  • 2
  • 4