react line chart in typescript

To render a line chart in a React application with Typescript, first install the necessary packages:

index.ts
npm install react-chartjs-2 chart.js --save
44 chars
2 lines

Once installed, import the necessary components into your React component file:

index.ts
import { Line } from 'react-chartjs-2';
import Chart from 'chart.js';
70 chars
3 lines

Then define a data object with your desired chart data, options for the chart, and a reference to the canvas element:

index.ts
const data = {
  labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
  datasets: [
    {
      label: 'My First Dataset',
      data: [65, 59, 80, 81, 56, 55, 40],
      fill: false,
      backgroundColor: 'rgb(255, 99, 132)',
      borderColor: 'rgba(255, 99, 132, 0.2)',
    },
  ],
};

const options = {
  responsive: true,
  scales: {
    yAxes: [
      {
        ticks: {
          beginAtZero: true,
        },
      },
    ],
  },
};

const ref = React.createRef<HTMLCanvasElement>();
514 chars
28 lines

Finally, render the chart component with the data, options, and reference props:

index.ts
<Line data={data} options={options} ref={ref} />
49 chars
2 lines

Note: Make sure to set the width and height of the canvas element to prevent rendering issues.

This is all you need to render a line chart in a React application with Typescript using Chart.js library.

gistlibby LogSnag