<Chart
className="max-w-100"
config={{
type: "bar",
data: {
labels: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
],
datasets: [
{
label: "Html Template",
maxBarThickness: 12,
data: [
60, 150, 30, 200, 180, 50, 180, 120, 230, 180, 250,
270,
],
backgroundColor: () => getColor("--color-primary", 0.3),
borderColor: () => getColor("--color-primary"),
borderWidth: 1,
},
],
},
options: {
maintainAspectRatio: false,
plugins: {
legend: {
display: false,
},
},
scales: {
x: {
display: false,
},
y: {
display: false,
},
},
},
}}
/>
Install the following dependencies:
Copy and paste the following code into your project.
import ChartJs from "chart.js/auto";
import { useRef, useEffect } from "react";
import { twMerge } from "tailwind-merge";
function getColor(name: string, opacity = 1) {
const color = getComputedStyle(document.documentElement)
.getPropertyValue(name)
.trim();
if (opacity < 1) {
return `color-mix(in oklch, ${color} ${opacity * 100}%, transparent ${
100 - opacity * 100
}%)`;
}
return color;
}
function Chart({
className,
config,
...props
}: React.ComponentProps<"canvas"> & {
config: ConstructorParameters<typeof ChartJs>[1];
}) {
const chartRef = useRef<
HTMLCanvasElement & {
instance?: {};
}
>(null);
useEffect(() => {
if (chartRef.current && !chartRef.current.instance) {
chartRef.current.instance = new ChartJs(chartRef.current, config);
}
}, []);
return (
<div className={twMerge("relative h-64 w-full", className)}>
<canvas ref={chartRef} {...props} />
</div>
);
}
export { Chart, getColor };
Update the import paths to match your project setup.
import { Chart, getColor } from "@/components/ui/chart";
<Chart
className="max-w-100"
config={{
type: "bar",
data: {
labels: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
],
datasets: [
{
label: "Html Template",
maxBarThickness: 12,
data: [
60, 150, 30, 200, 180, 50, 180, 120, 230, 180, 250,
270,
],
backgroundColor: () => getColor("--color-primary", 0.3),
borderColor: () => getColor("--color-primary"),
borderWidth: 1,
},
],
},
options: {
maintainAspectRatio: false,
plugins: {
legend: {
display: false,
},
},
scales: {
x: {
display: false,
},
y: {
display: false,
},
},
},
}}
/>