Chart

Beautiful charts. Built using Chartjs. Copy and paste into your apps.
Installation

Install the following dependencies:

pnpm
npm
yarn
bun
yarn add chart.js

Copy and paste the following code into your project.

components/ui/chart.tsx
Expand

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 };
 
Expand

Update the import paths to match your project setup.

Usage
Expand

import { Chart, getColor } from "@/components/ui/chart";
 
Expand
Expand

<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,
        },
      },
    },
  }}
/>
 
Expand
Powered by synthetic caffeine · Deployed by Left4code · Signal traceable on GitHub.