Skip to content

Instantly share code, notes, and snippets.

@nestarz
Created August 21, 2020 10:34
Show Gist options
  • Save nestarz/d083fef7877873b07e3b53137da69038 to your computer and use it in GitHub Desktop.
Save nestarz/d083fef7877873b07e3b53137da69038 to your computer and use it in GitHub Desktop.
Chart.js 3.x + React
import React, { useState, useEffect, useRef, memo } from "react";
import {
Chart,
Line,
LineController,
LinearScale,
LogarithmicScale,
PieController,
Point,
PolarAreaController,
RadarController,
RadialLinearScale,
Rectangle,
ScatterController,
DoughnutController,
BubbleController,
Arc,
BarController,
CategoryScale,
} from "chart.js";
Chart.register(
Arc,
BarController,
BubbleController,
CategoryScale,
DoughnutController,
Line,
LineController,
LinearScale,
RadialLinearScale,
LogarithmicScale,
PieController,
Point,
PolarAreaController,
RadarController,
RadialLinearScale,
Rectangle,
ScatterController
);
export default memo(({ type, data, options }) => {
const canvas = useRef(null);
const [chart, setChart] = useState(null);
useEffect(() => {
if (canvas.current) {
setChart(
new Chart(canvas.current.getContext("2d"), {
type,
data,
options,
})
);
}
return () => chart && chart.destroy();
}, [type]);
useEffect(() => {
if (chart) {
chart.options = options
? Object.assign(chart.options, options)
: chart.options;
chart.config.data = data;
chart.update();
}
}, [data, options]);
return (
<div className="chartjs-wrapper">
<canvas
ref={canvas}
className="chartjs"
style={{ maxWidth: "100%", objectFit: "contain" }}
></canvas>
</div>
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment