Last active
June 5, 2023 11:52
-
-
Save ayame113/c6e2e0f69dc9b05174330f2a229d0c5b to your computer and use it in GitHub Desktop.
Fresh + Chart.js client-side rendering
This file contains hidden or 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
| export * from "https://esm.sh/[email protected]"; | |
| import { Chart } from "https://esm.sh/[email protected]"; | |
| import { useEffect, useRef } from "preact/hooks"; | |
| import { JSX } from "preact"; | |
| interface ChartJsChartProps extends JSX.HTMLAttributes<HTMLCanvasElement> { | |
| config: ConstructorParameters<typeof Chart>[1]; | |
| } | |
| /** | |
| * ```ts ignore | |
| * import { | |
| * CategoryScale, | |
| * Chart, | |
| * ChartJsChart, | |
| * LinearScale, | |
| * LineController, | |
| * LineElement, | |
| * PointElement, | |
| * } from "../components/Chart.tsx"; | |
| * | |
| * Chart.register( | |
| * LineController, | |
| * LineElement, | |
| * PointElement, | |
| * CategoryScale, | |
| * LinearScale, | |
| * ); | |
| * | |
| * <ChartJsChart | |
| * config={{ | |
| * type: "line", | |
| * data: { | |
| * labels: ["1", "2", "3"], | |
| * datasets: [{ | |
| * label: "Sessions", | |
| * data: [123, 234, 234], | |
| * borderColor: "red", | |
| * backgroundColor: "red", | |
| * borderWidth: 1, | |
| * }, { | |
| * label: "Users", | |
| * data: [346, 233, 123], | |
| * borderColor: "blue", | |
| * backgroundColor: "red", | |
| * borderWidth: 1, | |
| * }], | |
| * }, | |
| * options: { | |
| * devicePixelRatio: 1, | |
| * scales: { yAxes: { beginAtZero: true } }, | |
| * }, | |
| * }} | |
| * /> | |
| * ``` | |
| */ | |
| export function ChartJsChart({ config, ...props }: ChartJsChartProps) { | |
| const ref = useRef<HTMLCanvasElement | null>(null); | |
| useEffect(() => { | |
| const chart = ref.current ? new Chart(ref.current, config) : undefined; | |
| return () => chart?.destroy(); | |
| }, []); | |
| return <canvas ref={ref} {...props} />; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment