Created
February 14, 2022 18:39
-
-
Save blackmann/50fb84989fb8ccf9468dcf33723ea755 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Chart from 'chart.js' | |
import { useEffect, useRef } from 'react' | |
/** | |
* @param {object} props | |
* @param {{label: string, value: string}[]} props.data | |
*/ | |
function DataChart({ data, id, graphColor = '#68AC67', label, type = 'bar' }) { | |
const oldChart = useRef() | |
const chartRef = useRef() | |
useEffect(() => { | |
const ctx = chartRef | |
const labels = data.map((d) => d.label) | |
oldChart.current?.destroy() | |
oldChart.current = new Chart(ctx, { | |
data: { | |
datasets: [ | |
{ | |
backgroundColor: graphColor, | |
borderColor: graphColor, | |
data: data.map((d) => d.value), | |
fill: type === 'bar', | |
label, | |
lineTension: 0, | |
}, | |
], | |
labels, | |
}, | |
options: { | |
legend: { | |
display: false, | |
}, | |
responsive: true, | |
scales: { | |
yAxes: [ | |
{ | |
ticks: { | |
beginAtZero: true, | |
precision: 0, | |
}, | |
}, | |
], | |
}, | |
}, | |
type, | |
}) | |
}, [data, label, id, type, graphColor]) | |
return ( | |
<canvas id={id} style={{ position: 'relative', width: '400px' }} className="ratio ratio-16x9" ref={chartRef} /> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment