There are three different ways to import dependencies in react-chartjs-2 before creating our chart:
The laziest way - import all dependencies from Chart.js .
The tree-shakable way - import only what is needed for the specific chart.
The tree-shakable typed chart components - no need for a controller.
lazy way import 'chart.js/auto' ;
import { Chart } from 'react-chartjs-2' ;
< Chart type = 'line' data = {chartData} />
When you use Chart
as your chart component, it’s almost the same way to implement tree-shaking in native Chart.js .
tree-shakable way import {
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Legend,
Tooltip,
Chart as ChartJS,
LineController,
} from "chart.js" ;
import { Chart } from "react-chartjs-2" ;
ChartJS. register (
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Legend,
Tooltip,
LineController
);
< Chart type = "line" data = {data} options = {options} />
When you use Line
or any other chart component instead of Chart
, you can simply omit the import of its controller. For example, there’s no need to register LineController
when you use Line
instead of Chart
.
typed chart components import {
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Legend,
Tooltip,
Chart as ChartJS,
} from "chart.js" ;
import { Line } from "react-chartjs-2" ;
ChartJS. register (
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Legend,
Tooltip,
);
< Line data = {data} options = {options} />