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>
    );
};
0

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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} />;
    }
  })()}
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.