Chart
The recharts wrapper every kit chart is drawn in: series colours from a config, a tooltip and a legend.
Vibra strokes the cartesian grid in --chart-grid rather than --border at half strength, and draws the tooltip as the kit's elev-1 floating layer rather than a bordered box on --background with shadow-xl. ChartContainer writes a --color-<key> custom property for each series in its config, so a series is coloured var(--color-revenue); the kit's AreaChart, LineChart and the rest are built on it. It measures its own box before it draws: a chart mounts at the size it will be shown at rather than at 320×200 and then snapping, and a box with no area — a StatCard footer hidden on a phone, a closed tab, a collapsed panel — holds no chart at all until it has one, so a hidden chart costs nothing and recharts never logs its width(0)/height(0) warning. The server renders the empty box, and the chart arrives with the first client frame. The kit's charts name themselves once — the container is role="img" with a summary and a data twin beside it — and pass accessibilityLayer={false} and isAnimationActive={false} to recharts: its keyboard layer would make every chart surface an unnamed role="application" tab stop inside that image, and its draw-in answers only the OS setting, not [data-motion="reduced"]. A chart you compose yourself with no text twin can keep recharts' layer.
Install
npx shadcn@latest add @vibra/chartNeeds the @vibra registry in your components.json — set it up once.
Examples
"use client"
import { CartesianGrid, Line, LineChart, XAxis, YAxis } from "recharts"
import { ChartContainer, ChartTooltip, ChartTooltipContent, type ChartConfig } from "@/components/ui/chart"
const SIGNUPS = [
{ week: "Jul 6", signups: 184 },
{ week: "Jul 13", signups: 197 },
{ week: "Jul 20", signups: 176 },
{ week: "Jul 27", signups: 221 },
{ week: "Aug 3", signups: 238 },
{ week: "Aug 10", signups: 229 },
{ week: "Aug 17", signups: 264 },
{ week: "Aug 24", signups: 281 },
{ week: "Aug 31", signups: 259 },
{ week: "Sep 7", signups: 302 },
{ week: "Sep 14", signups: 318 },
]
// One series, so it is drawn in the first chart slot — a grey in the default
// palette, the accent's colour where the accent is one.
const config = {
signups: { label: "Sign-ups", color: "var(--chart-1)" },
} satisfies ChartConfig
export default function ChartDemo() {
return (
<figure className="flex w-full max-w-lg flex-col gap-2">
<figcaption className="text-sm font-medium">Weekly sign-ups</figcaption>
<ChartContainer config={config} className="aspect-auto h-52 w-full">
<LineChart data={SIGNUPS} margin={{ top: 8, right: 8, left: 0, bottom: 0 }} accessibilityLayer>
<CartesianGrid vertical={false} strokeDasharray="4 4" />
<XAxis dataKey="week" tickLine={false} axisLine={false} tickMargin={8} minTickGap={24} />
<YAxis width={36} tickLine={false} axisLine={false} tickMargin={4} />
<ChartTooltip cursor={false} content={<ChartTooltipContent indicator="line" />} />
<Line
dataKey="signups"
type="monotone"
stroke="var(--color-signups)"
strokeWidth={2}
dot={false}
isAnimationActive={false}
/>
</LineChart>
</ChartContainer>
</figure>
)
}Props
| Prop | Type | Default | Description |
|---|---|---|---|
| ChartContainer.config | ChartConfig | — | Each series by key: its label, and a color — or a theme of light and dark colours. |
| ChartContainer.initialDimension | { width: number; height: number } | { width: 320, height: 200 } | The size recharts draws at where the container cannot measure itself — no ResizeObserver, as in a test runner. In a browser it measures its box and draws at that size. |
| ChartTooltipContent.indicator | "dot" | "line" | "dashed" | "dot" | The swatch beside each value in the tooltip. |
| ChartTooltipContent.hideLabel / hideIndicator | boolean | false | Drops the tooltip's heading, or the swatches. |
| ChartLegendContent.nameKey | string | — | The config key a legend entry is named from, when it is not the dataKey. |
Dependencies
Registry
npm
Source
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
import * as RechartsPrimitive from "recharts"
import type { TooltipValueType } from "recharts"
// Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = { light: "", dark: ".dark" } as const
const INITIAL_DIMENSION = { width: 320, height: 200 } as const
type TooltipNameType = number | string
export type ChartConfig = Record<
string,
{
label?: React.ReactNode
icon?: React.ComponentType
} & (
| { color?: string; theme?: never }
| { color?: never; theme: Record<keyof typeof THEMES, string> }
)
>
type ChartContextProps = {
config: ChartConfig
}
const ChartContext = React.createContext<ChartContextProps | null>(null)
function useChart() {
const context = React.useContext(ChartContext)
if (!context) {
throw new Error("useChart must be used within a <ChartContainer />")
}
return context
}
/**
* What the container knows about its own box: nothing yet (on the server and
* in the first client render), that it has no area, its size, or that it
* cannot be measured at all because there is no ResizeObserver to watch it.
*/
type ChartBox =
| { status: "unmeasured" | "empty" | "unmeasurable" }
| { status: "sized"; width: number; height: number }
const UNMEASURED: ChartBox = { status: "unmeasured" }
const EMPTY: ChartBox = { status: "empty" }
const UNMEASURABLE: ChartBox = { status: "unmeasurable" }
// Only the edge between no area and some changes the box: a resize inside a
// drawn box is recharts' own to follow, and re-rendering the chart for it here
// would draw it twice.
function nextBox(current: ChartBox, width: number, height: number): ChartBox {
const [w, h] = [Math.round(width), Math.round(height)]
if (w > 0 && h > 0) return current.status === "sized" ? current : { status: "sized", width: w, height: h }
return current.status === "empty" ? current : EMPTY
}
function ChartContainer({
id,
className,
children,
config,
initialDimension = INITIAL_DIMENSION,
ref,
...props
}: React.ComponentProps<"div"> & {
config: ChartConfig
children: React.ComponentProps<
typeof RechartsPrimitive.ResponsiveContainer
>["children"]
initialDimension?: {
width: number
height: number
}
}) {
const uniqueId = React.useId()
const chartId = `chart-${id ?? uniqueId.replace(/:/g, "")}`
const [box, setBox] = React.useState<ChartBox>(UNMEASURED)
// Measured before anything is drawn. A box with no area — a footer hidden
// on a phone, a closed tab, a collapsed panel — holds no chart at all rather
// than one recharts measures at 0×0 and warns about, and a box with one gets
// its chart at that size from the first frame, not at recharts' 320×200 for
// a frame and then snapped. Without a ResizeObserver (a test runner) there
// is nothing to measure with, so recharts draws at initialDimension.
const measure = React.useCallback(
(node: HTMLDivElement | null) => {
if (typeof ref === "function") ref(node)
else if (ref) ref.current = node
if (!node) return
if (typeof ResizeObserver !== "function") {
setBox(UNMEASURABLE)
return
}
const read = (width: number, height: number) => setBox((current) => nextBox(current, width, height))
const rect = node.getBoundingClientRect()
read(rect.width, rect.height)
const observer = new ResizeObserver(([entry]) => {
if (entry) read(entry.contentRect.width, entry.contentRect.height)
})
observer.observe(node)
return () => {
observer.disconnect()
if (typeof ref === "function") ref(null)
else if (ref) ref.current = null
}
},
[ref]
)
return (
<ChartContext.Provider value={{ config }}>
<div
ref={measure}
data-slot="chart"
data-chart={chartId}
className={cn(
"flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-(--chart-grid) [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
className
)}
{...props}
>
<ChartStyle id={chartId} config={config} />
{box.status === "sized" || box.status === "unmeasurable" ? (
<RechartsPrimitive.ResponsiveContainer
initialDimension={
box.status === "sized" ? { width: box.width, height: box.height } : initialDimension
}
>
{children}
</RechartsPrimitive.ResponsiveContainer>
) : null}
</div>
</ChartContext.Provider>
)
}
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
const colorConfig = Object.entries(config).filter(
([, config]) => config.theme ?? config.color
)
if (!colorConfig.length) {
return null
}
return (
<style
dangerouslySetInnerHTML={{
__html: Object.entries(THEMES)
.map(
([theme, prefix]) => `
${prefix} [data-chart=${id}] {
${colorConfig
.map(([key, itemConfig]) => {
const color =
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ??
itemConfig.color
return color ? ` --color-${key}: ${color};` : null
})
.join("\n")}
}
`
)
.join("\n"),
}}
/>
)
}
const ChartTooltip = RechartsPrimitive.Tooltip
function ChartTooltipContent({
active,
payload,
className,
indicator = "dot",
hideLabel = false,
hideIndicator = false,
label,
labelFormatter,
labelClassName,
formatter,
color,
nameKey,
labelKey,
}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
React.ComponentProps<"div"> & {
hideLabel?: boolean
hideIndicator?: boolean
indicator?: "line" | "dot" | "dashed"
nameKey?: string
labelKey?: string
} & Omit<
RechartsPrimitive.DefaultTooltipContentProps<
TooltipValueType,
TooltipNameType
>,
"accessibilityLayer"
>) {
const { config } = useChart()
const tooltipLabel = React.useMemo(() => {
if (hideLabel || !payload?.length) {
return null
}
const [item] = payload
const key = `${labelKey ?? item?.dataKey ?? item?.name ?? "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const value =
!labelKey && typeof label === "string"
? (config[label]?.label ?? label)
: itemConfig?.label
if (labelFormatter) {
return (
<div className={cn("font-medium", labelClassName)}>
{labelFormatter(value, payload)}
</div>
)
}
if (!value) {
return null
}
return <div className={cn("font-medium", labelClassName)}>{value}</div>
}, [
label,
labelFormatter,
payload,
hideLabel,
labelClassName,
config,
labelKey,
])
if (!active || !payload?.length) {
return null
}
const nestLabel = payload.length === 1 && indicator !== "dot"
return (
<div
className={cn(
// A floating layer, so it takes the same recipe every other one takes:
// elev-1 is the popover plane, the hairline ring and the float shadow.
// It used to be bg-background — off-white on a white card in light, and
// the darkest object on the page in dark.
"grid min-w-32 items-start gap-1.5 elev-1 px-2.5 py-1.5 text-xs",
className
)}
>
{!nestLabel ? tooltipLabel : null}
<div className="grid gap-1.5">
{payload
.filter((item) => item.type !== "none")
.map((item, index) => {
const key = `${nameKey ?? item.name ?? item.dataKey ?? "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const indicatorColor = color ?? item.payload?.fill ?? item.color
return (
<div
key={index}
className={cn(
"flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",
indicator === "dot" && "items-center"
)}
>
{formatter && item?.value !== undefined && item.name ? (
formatter(item.value, item.name, item, index, item.payload)
) : (
<>
{itemConfig?.icon ? (
<itemConfig.icon />
) : (
!hideIndicator && (
<div
className={cn(
"shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)",
{
"h-2.5 w-2.5": indicator === "dot",
"w-1": indicator === "line",
"w-0 border-[1.5px] border-dashed bg-transparent":
indicator === "dashed",
"my-0.5": nestLabel && indicator === "dashed",
}
)}
style={
{
"--color-bg": indicatorColor,
"--color-border": indicatorColor,
} as React.CSSProperties
}
/>
)
)}
<div
className={cn(
"flex flex-1 justify-between leading-none",
nestLabel ? "items-end" : "items-center"
)}
>
<div className="grid gap-1.5">
{nestLabel ? tooltipLabel : null}
<span className="text-muted-foreground">
{itemConfig?.label ?? item.name}
</span>
</div>
{item.value != null && (
<span className="font-mono font-medium text-foreground tabular-nums">
{typeof item.value === "number"
? item.value.toLocaleString()
: String(item.value)}
</span>
)}
</div>
</>
)}
</div>
)
})}
</div>
</div>
)
}
const ChartLegend = RechartsPrimitive.Legend
function ChartLegendContent({
className,
hideIcon = false,
payload,
verticalAlign = "bottom",
nameKey,
}: React.ComponentProps<"div"> & {
hideIcon?: boolean
nameKey?: string
} & RechartsPrimitive.DefaultLegendContentProps) {
const { config } = useChart()
if (!payload?.length) {
return null
}
return (
<div
className={cn(
"flex items-center justify-center gap-4",
verticalAlign === "top" ? "pb-3" : "pt-3",
className
)}
>
{payload
.filter((item) => item.type !== "none")
.map((item, index) => {
const key = `${nameKey ?? item.dataKey ?? "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
return (
<div
key={index}
className={cn(
"flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"
)}
>
{itemConfig?.icon && !hideIcon ? (
<itemConfig.icon />
) : (
<div
className="h-2 w-2 shrink-0 rounded-[2px]"
style={{
backgroundColor: item.color,
}}
/>
)}
{itemConfig?.label}
</div>
)
})}
</div>
)
}
function getPayloadConfigFromPayload(
config: ChartConfig,
payload: unknown,
key: string
) {
if (typeof payload !== "object" || payload === null) {
return undefined
}
const payloadPayload =
"payload" in payload &&
typeof payload.payload === "object" &&
payload.payload !== null
? payload.payload
: undefined
let configLabelKey: string = key
if (
key in payload &&
typeof payload[key as keyof typeof payload] === "string"
) {
configLabelKey = payload[key as keyof typeof payload] as string
} else if (
payloadPayload &&
key in payloadPayload &&
typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
) {
configLabelKey = payloadPayload[
key as keyof typeof payloadPayload
] as string
}
return configLabelKey in config ? config[configLabelKey] : config[key]
}
export {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
ChartLegend,
ChartLegendContent,
ChartStyle,
}