Line Chart
ChartsLine chart with data points and grid.
Preview
Usage
example.jsx
import { LineChart } from "@/components/ui/line-chart";
export default function Example() {
return <LineChart />;
}Source Code
Copy this file into components/ui/line-chart.jsx in your project.
line-chart.jsx
"use client";
import { forwardRef } from "react";
import { cn } from "@/lib/utils";
const LineChart = forwardRef(({ className, data = [], width = 400, height = 250, lineColor = "var(--primary)", ...props }, ref) => {
const maxVal = Math.max(...data.map((d) => d.value), 1);
const minVal = Math.min(...data.map((d) => d.value), 0);
const range = maxVal - minVal || 1;
const padX = 50, padY = 20;
const chartW = width - padX - 10;
const chartH = height - padY * 2 - 10;
const points = data.map((d, i) => ({
x: padX + (i / (data.length - 1 || 1)) * chartW,
y: padY + chartH - ((d.value - minVal) / range) * chartH,
}));
const pathD = points.map((p, i) => `${i === 0 ? "M" : "L"}${p.x},${p.y}`).join(" ");
return (
<div ref={ref} className={cn("inline-block", className)} {...props}>
<svg width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
<line x1={padX} y1={padY} x2={padX} y2={height - padY - 10} stroke="currentColor" opacity="0.2" />
<line x1={padX} y1={height - padY - 10} x2={width - 10} y2={height - padY - 10} stroke="currentColor" opacity="0.2" />
<path d={pathD} fill="none" stroke={lineColor} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
{points.map((p, i) => (
<g key={i}>
<circle cx={p.x} cy={p.y} r="3" fill={lineColor} />
<text x={p.x} y={height - 8} textAnchor="middle" className="fill-muted-foreground text-[10px]">{data[i].label}</text>
</g>
))}
</svg>
</div>
);
});
LineChart.displayName = "LineChart";
export { LineChart };
Quick Install
Make sure you have the cn() utility set up. It requires clsx and tailwind-merge.
npm install clsx tailwind-merge