Charts
LineChart and CategoryBarChart show one metric each: a headline, a change badge against the previous period, the plot, and a footer link. Lines stop at the last bucket that has started, and useInViewFetch holds a chart's request until it scrolls into view.
@dentil/charts- Free1,284
- Starter642
- Pro318
- Enterprise41
'use client';
import { CategoryBarChart } from '@/components/dentil/charts/category-bar-chart';
import { LineChart } from '@/components/dentil/charts/line-chart';
import { DEMO_NOW, DEMO_UPDATED_AT, revenue, revenueTotals, subscriptionsByPlan } from '@/lib/demo/charts';
const currency = new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'GBP' });
const formatPence = (pence: number) => currency.format(pence / 100);
export function ChartsOverviewDemo() {
return (
<div className="grid gap-6 md:grid-cols-[3fr_2fr] md:gap-0 md:divide-x">
<LineChart
title="Revenue"
value={revenueTotals.current}
previousValue={revenueTotals.previous}
formatValue={formatPence}
data={revenue}
series={[
{ key: 'value', label: 'This period' },
{ key: 'previous', label: 'Previous period', comparison: true, dateKey: 'previousDate' },
]}
unit="day"
now={DEMO_NOW}
timezone="Europe/London"
locale="en-GB"
href="#examples"
updatedAt={DEMO_UPDATED_AT}
className="md:pr-6"
/>
<CategoryBarChart
title="Subscriptions by plan"
meta="Today"
items={subscriptionsByPlan}
locale="en-GB"
className="md:pl-6"
/>
</div>
);
}Installation
pnpm dlx shadcn@latest add @dentil/chartsnpx shadcn@latest add @dentil/chartsyarn dlx shadcn@latest add @dentil/chartsbunx --bun shadcn@latest add @dentil/chartsFiles land in components/dentil/charts/. It uses the stock shadcn chart component, which adds Recharts 3, plus @dentil/badge and @dentil/link. Colors come from your theme's --chart-1 to --chart-5.
Usage
Pass the totals you already have as value and previousValue, and the change badge follows. Charts have no border or padding, so place them in your own card or grid cell.
import NextLink from 'next/link';
import { LineChart } from '@/components/dentil/charts/line-chart';
import { useInViewFetch } from '@/components/dentil/charts/use-in-view-fetch';
const { ref } = useInViewFetch(() => load(range), [range.start, range.end]);
<div ref={ref} className="rounded-lg border p-6">
<LineChart
title="Revenue"
value={totals.current}
previousValue={totals.previous}
formatValue={(pence) => currency.format(pence / 100)}
data={points}
series={[
{ key: 'value', label: 'This period' },
{ key: 'previous', label: 'Previous period', comparison: true, dateKey: 'previousDate' },
]}
unit="day"
timezone="Europe/London"
loading={loading}
href="/payments"
updatedAt={lastUpdated}
linkComponent={NextLink}
/>
</div>Data
Each point carries its bucket start as date, in unix seconds, milliseconds, an ISO string or a Date. Formatting happens at render time in timezone, so you don't format labels yourself. Points after now are cut off on the main lines, because reporting APIs usually fill future buckets with 0, which would read as a real drop. Comparison lines run the full width.
// One point per bucket. `date` is the bucket start.
const points = [
{ date: 1794787200, value: 3_412_000, previous: 2_980_000, previousDate: 1792108800 }, // 16 Nov
{ date: 1794873600, value: 3_190_500, previous: 3_105_000, previousDate: 1792195200 }, // 17 Nov, today
{ date: 1794960000, value: 0, previous: 2_870_000, previousDate: 1792281600 }, // 18 Nov, cut off
];Examples
Several lines
A string headline with its own change badge. Failed uses the theme’s destructive color. Hover to see both values for a day.
'use client';
import { getPercentChange } from '@/components/dentil/charts/percent-change';
import { LineChart } from '@/components/dentil/charts/line-chart';
import { apiRequests, DEMO_UPDATED_AT, successRate } from '@/lib/demo/charts';
const percent = (rate: number) => `${(rate * 100).toFixed(1)}%`;
export function ChartsMultiLineDemo() {
return (
<LineChart
title="API requests"
value={`${percent(successRate.current)} success rate`}
previousLabel={`${percent(successRate.previous)} previous period`}
change={getPercentChange(successRate.current, successRate.previous)}
data={apiRequests}
series={[
{ key: 'succeeded', label: 'Succeeded', color: 'var(--chart-2)' },
{ key: 'failed', label: 'Failed', color: 'var(--destructive)' },
]}
unit="day"
showYAxis
timezone="Europe/London"
locale="en-GB"
updatedAt={DEMO_UPDATED_AT}
/>
);
}Category bar
Rows link elsewhere. With lowerIsBetter, fewer open tickets than last week reads as green.
'use client';
import { CategoryBarChart } from '@/components/dentil/charts/category-bar-chart';
import { DEMO_UPDATED_AT, ticketAges } from '@/lib/demo/charts';
export function ChartsCategoryBarDemo() {
return (
<CategoryBarChart
title="Open tickets by age"
items={ticketAges}
formatValue={(count) => `${count} ${count === 1 ? 'ticket' : 'tickets'}`}
formatHeadlineValue={(count) => count.toLocaleString('en-GB')}
previousValue={48}
lowerIsBetter
locale="en-GB"
timezone="Europe/London"
href="#api"
updatedAt={DEMO_UPDATED_AT}
/>
);
}States
Loading, error, empty, and embedded inside another surface without its title or footer.
'use client';
import { LineChart } from '@/components/dentil/charts/line-chart';
import { DEMO_NOW, revenue, revenueTotals } from '@/lib/demo/charts';
const currency = new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'GBP', notation: 'compact' });
const formatPence = (pence: number) => currency.format(pence / 100);
const series = [
{ key: 'value', label: 'This period' },
{ key: 'previous', label: 'Previous period', comparison: true, dateKey: 'previousDate' },
];
export function ChartsStatesDemo() {
return (
<div className="grid gap-x-6 gap-y-8 sm:grid-cols-2">
<LineChart title="Loading" data={[]} series={series} loading />
<LineChart title="Error" data={[]} series={series} error="Couldn’t load this report. Try again later." />
<LineChart title="No data" value={0} data={[]} series={series} locale="en-GB" />
<div className="flex flex-col gap-2">
<div className="text-muted-foreground text-sm">Embedded</div>
<div className="rounded-lg border p-3">
<LineChart
embedded
value={revenueTotals.current}
previousValue={revenueTotals.previous}
formatValue={formatPence}
data={revenue}
series={series}
now={DEMO_NOW}
timezone="Europe/London"
locale="en-GB"
/>
</div>
</div>
</div>
);
}Fetch in view
The request starts when the chart scrolls into view. Switch the range to fetch again; scrolling away and back doesn’t.
Result: 0 fetches
'use client';
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { LineChart } from '@/components/dentil/charts/line-chart';
import { useInViewFetch } from '@/components/dentil/charts/use-in-view-fetch';
import { apiRequests } from '@/lib/demo/charts';
type Range = '7d' | '14d';
async function fetchRequests(range: Range) {
await new Promise((resolve) => setTimeout(resolve, 800));
return range === '7d' ? apiRequests.slice(-7) : apiRequests;
}
export function ChartsInViewDemo() {
const [range, setRange] = useState<Range>('14d');
const [data, setData] = useState<typeof apiRequests>([]);
const [loading, setLoading] = useState(true);
const [fetches, setFetches] = useState(0);
const { ref } = useInViewFetch(async () => {
setLoading(true);
setFetches((count) => count + 1);
setData(await fetchRequests(range));
setLoading(false);
}, [range]);
const total = data.reduce((sum, point) => sum + point.succeeded + point.failed, 0);
return (
<div ref={ref} className="flex flex-col gap-4">
<div className="flex items-center gap-2">
{(['7d', '14d'] as const).map((option) => (
<Button
key={option}
size="sm"
variant={range === option ? 'secondary' : 'ghost'}
aria-pressed={range === option}
onClick={() => setRange(option)}>
Last {option.replace('d', ' days')}
</Button>
))}
<p className="text-muted-foreground ml-auto text-sm">
Result: <code className="text-foreground">{fetches} fetches</code>
</p>
</div>
<LineChart
title="API requests"
value={loading ? undefined : total}
data={data}
series={[
{ key: 'succeeded', label: 'Succeeded', color: 'var(--chart-2)' },
{ key: 'failed', label: 'Failed', color: 'var(--destructive)' },
]}
loading={loading}
timezone="Europe/London"
locale="en-GB"
/>
</div>
);
}Composing
The presets are built from Chart, ChartHeader, ChartContent and ChartFooter in chart.tsx. Use them around any Recharts plot to keep the same header, states and footer. Chart passes loading, embedded, timezone, locale and linkComponent down to the parts.
import { Bar, BarChart, XAxis } from 'recharts';
import { Chart, ChartContent, ChartFooter, ChartHeader } from '@/components/dentil/charts/chart';
import { ChartContainer } from '@/components/ui/chart';
<Chart loading={loading} linkComponent={NextLink}>
<ChartHeader title="Refunds" value={total} previousValue={previous} lowerIsBetter formatValue={formatPence} />
<ChartContent error={error} empty={weeks.length === 0}>
<ChartContainer config={{ amount: { label: 'Refunds', color: 'var(--chart-1)' } }} className="aspect-auto h-60 w-full">
<BarChart data={weeks}>
<XAxis dataKey="week" tickLine={false} axisLine={false} />
<Bar dataKey="amount" fill="var(--color-amount)" radius={4} />
</BarChart>
</ChartContainer>
</ChartContent>
<ChartFooter href="/payments?status=refunded" updatedAt={lastUpdated} />
</Chart>API reference
LineChart
| Prop | Type | Default | Description |
|---|---|---|---|
| data | ChartPoint[] | — | One point per bucket: date plus a field per series key and per dateKey. A null value leaves a gap. |
| series | ChartSeries[] | — | The lines to draw, in tooltip order. See ChartSeries below. |
| unit | 'hour' | 'day' | 'week' | 'month' | 'day' | Bucket size. Picks the date format: 14:00, 3 Nov 26, or Nov 26. |
| formatValue | (value: number) => string | toLocaleString | Formats the headline, the previous value and tooltip values. |
| formatDate | (date: ChartDate) => string | — | Formats axis and tooltip dates. Defaults to formatChartDate with unit, timezone and locale. |
| formatAxisValue | (value: number) => string | formatCompactNumber | Formats y-axis ticks, such as 12.3K. |
| showXAxis | boolean | true | Shows the first and last dates. |
| showYAxis | boolean | false | Shows zero and the maximum value. |
| now | number | string | Date | Date.now() | Points after this are cut off on non-comparison lines. Set it to freeze a server-rendered chart. |
| error | ReactNode | — | Replaces the plot with an error message. |
| emptyMessage | ReactNode | 'No data' | Shown when data is empty. |
| … | Chart, ChartHeader and ChartFooter props | — | loading, embedded, timezone, locale, linkComponent, className, the headline props and href, hrefLabel and updatedAt. |
ChartSeries
| Prop | Type | Default | Description |
|---|---|---|---|
| key | string | — | Field on each point that holds this line’s value. |
| label | string | — | Tooltip label. |
| color | string | — | Any CSS color. Defaults to var(--chart-1) through var(--chart-5) in order, or muted gray for a comparison. |
| comparison | boolean | false | A previous-period line: drawn underneath with no hover dot, and never cut off at now. |
| dateKey | string | — | Field holding the date this value belongs to. When any series has one, tooltip rows are labelled with their own dates, so this period and the previous one read side by side. |
CategoryBarChart
| Prop | Type | Default | Description |
|---|---|---|---|
| items | CategoryBarItem[] | — | { id, title, subtitle?, value, href?, color? }. Items with href render as links with linkComponent. Colors default to the theme chart colors in order. |
| value | ReactNode | sum of items | Headline. |
| formatValue | (value: number) => string | toLocaleString | Formats each row’s value. |
| formatHeadlineValue | (value: number) => string | formatValue | Formats the headline, when rows read "18 tickets" but the headline is just "41". |
| … | Same as LineChart | — | Chart, headline and footer props, error and emptyMessage. |
Chart
| Prop | Type | Default | Description |
|---|---|---|---|
| loading | boolean | false | Shows a skeleton headline and a spinner in place of the plot. A part’s own loading prop overrides it. |
| embedded | boolean | false | Compact mode for a chart inside another surface. Hides the title, the "previous period" line and the footer, and uses a 160px plot instead of 240px. |
| timezone | string | — | IANA zone for axis, tooltip and footer times. Omit it to use the runtime zone. |
| locale | string | — | BCP 47 tag for dates and default number formatting. Set it when the page is server-rendered, so the server and browser agree. |
| linkComponent | LinkComponent | 'a' | Renders the footer link and category rows, for example next/link. The same type as @dentil/link. |
| className | string | — | Merged onto the root. It has no border or padding of its own. |
ChartHeader
| Prop | Type | Default | Description |
|---|---|---|---|
| title | ReactNode | — | Hidden when embedded. |
| meta | ReactNode | — | Muted text to the right of the title, such as "All time". |
| value | ReactNode | — | Headline. A number goes through formatValue. A string, such as "98.4% success rate", renders as is. Nothing is shown when it's undefined. |
| previousValue | number | — | The comparison period’s value. Adds the change badge and a "… previous period" line under the headline. |
| previousLabel | ReactNode | — | Replaces the "… previous period" line, for headlines that aren’t a single number. |
| formatValue | (value: number) => string | toLocaleString | Formats the headline and the previous value. |
| change | PercentChange | false | — | The badge. Worked out with getPercentChange when value and previousValue are both numbers. Pass your own for a string headline, or false to hide it. |
| lowerIsBetter | boolean | false | Colors a decrease green and an increase yellow, for churn, refunds or latency. |
ChartContent
| Prop | Type | Default | Description |
|---|---|---|---|
| error | ReactNode | — | Replaces the plot with a dashed box and this message. |
| empty | boolean | false | Replaces the plot with emptyMessage. |
| emptyMessage | ReactNode | 'No data' | Shown when empty is set. |
ChartFooter
| Prop | Type | Default | Description |
|---|---|---|---|
| href | string | — | Adds a "View more" link on the left. |
| hrefLabel | ReactNode | 'View more' | Link text. |
| updatedAt | number | string | Date | — | Shows "Last updated HH:mm" on the right. Numbers are unix seconds or milliseconds. |
useInViewFetch
| Prop | Type | Default | Description |
|---|---|---|---|
| fetch | () => void | Promise<void> | — | Called once the element is near the viewport. The latest function is always used. |
| deps | unknown[] | — | Fetch again when these change, compared with JSON.stringify. If they change while the chart is off screen, the fetch waits until it scrolls back. |
| options.rootMargin | string | '200px 0px' | Grows the viewport so loading starts just before the chart appears. |
| returns | { ref, inView } | — | Put ref on the chart’s wrapper element. |
Helpers
| Prop | Type | Default | Description |
|---|---|---|---|
| getPercentChange | (current, previous, { lowerIsBetter? }) => PercentChange | — | { label: '+12.5%', variant: 'green' }. Equal values are a zinc 0%, and a rise from zero reads as +100%. |
| formatChartDate | (date, { unit?, timezone?, locale? }) => string | — | The default axis and tooltip format, built on Intl.DateTimeFormat. |
| formatCompactNumber | (value, locale?) => string | — | The default y-axis format: 950, 12.3K, 4.5M. |
| maskFuture | (data, keys, now?) => data | — | Sets keys to null on points whose date is after now. LineChart calls it for you. |