-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathReactChart.tsx
78 lines (68 loc) · 1.54 KB
/
ReactChart.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import React, { useEffect, useRef, useCallback, useState } from 'react';
import { Chart } from 'chart.js';
import type {
ChartOptions,
ChartData,
ChartType,
Plugin,
UpdateMode,
} from 'chart.js';
import { generateID } from './utils/generate-id/generateID';
import { noop } from './utils/noop';
export interface ChartProps {
data: ChartData;
options: ChartOptions;
type: ChartType;
plugins?: Plugin[];
updateMode?: UpdateMode;
id?: string;
height?: number;
width?: number;
}
export const ReactChart = ({
id,
data,
options,
type,
plugins,
updateMode,
height,
width,
}: ChartProps) => {
const chartInstance = useRef<Chart>({
update: noop,
destroy: noop,
} as Chart);
const [CHART_ID] = useState(id || generateID('Chart'));
useEffect(() => {
chartInstance.current.data = data;
chartInstance.current.options = options;
chartInstance.current.update(updateMode);
}, [data, options]);
const nodeRef = useCallback<(node: HTMLCanvasElement | null) => void>(
(node) => {
chartInstance.current.destroy();
if (node) {
chartInstance.current = new Chart(node, {
type,
data,
options,
plugins,
});
}
},
[],
);
return (
<canvas
ref={nodeRef}
height={height}
width={width}
id={CHART_ID}
role="chart"
/>
);
};
// The `register` is a static method and can be safely bounded
// eslint-disable-next-line @typescript-eslint/unbound-method
ReactChart.register = Chart.register || noop;