Skip to content

Chart

Draws bar, line, area and pie charts with Recharts, coloured from the theme's chart tokens.

Units shipped per month, January to June. March to June average 2,583.

Installation

pnpm dlx shadcn@latest add @silkware/chart

To copy the component by hand, install its dependencies:

pnpm add recharts cn

Then copy the source into components/ui/chart.tsx:

components/ui/chart.tsx
"use client"
import * as React from "react"import { cn } from "cn"import * as RechartsPrimitive from "recharts"import type { TooltipValueType } from "recharts"
const THEMES = { light: "", dark: ".dark" } as const
const INITIAL_DIMENSION = { width: 320, height: 200 } as consttype TooltipNameType = number | string
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}
function ChartContainer({  id,  className,  children,  config,  initialDimension = INITIAL_DIMENSION,  ...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, "")}`
  return (    <ChartContext.Provider value={{ config }}>      <div        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-border/50 [&_.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} />        <RechartsPrimitive.ResponsiveContainer          initialDimension={initialDimension}        >          {children}        </RechartsPrimitive.ResponsiveContainer>      </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(        "grid min-w-32 items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",        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 {  type ChartConfig,  ChartContainer,  ChartTooltip,  ChartTooltipContent,  ChartLegend,  ChartLegendContent,  ChartStyle,}

Usage

import { Bar, BarChart, CartesianGrid, XAxis } from "recharts"
import {  ChartContainer,  ChartTooltip,  ChartTooltipContent,  type ChartConfig,} from "@/components/ui/chart"
const config = {  units: { label: "Units shipped", color: "var(--chart-1)" },} satisfies ChartConfig
<ChartContainer config={config} className="min-h-[200px] w-full">  <BarChart accessibilityLayer data={data}>    <CartesianGrid vertical={false} />    <XAxis dataKey="month" />    <ChartTooltip content={<ChartTooltipContent />} />    <Bar dataKey="units" fill="var(--color-units)" />  </BarChart></ChartContainer>

This component wraps Recharts version 3. You write the chart with Recharts parts, and ChartContainer adds the sizing, the theme colours and the context that the tooltip and the legend read.

Three things people get wrong:

  • Give the container a height. It is a responsive container, and without a min-h or a h class it collapses to nothing.
  • Refer to a series colour as var(--color-<key>), where the key is the one in config. ChartContainer defines these variables from the config. Do not put a raw colour on the series.
  • Put a text alternative next to every chart. See Accessibility.

Colour

The config's color takes any CSS colour. Use the theme tokens: var(--chart-1) to var(--chart-5). In the Silkware theme they are an ink ramp, from ink to silver in light mode and from white to iron in dark mode, so a chart reads in greyscale and in print.

--chart-1 
--chart-2 
--chart-3 
--chart-4 
--chart-5 

Crimson is reserved. The brand uses it once per screen, so a chart spends it on the one series the reader should look at, with var(--brand). Do not use it for several series, and do not use it for "bad" values: that meaning belongs to --destructive.

Tokens switch with the theme, so a chart that uses var(--chart-1) is correct in both modes with no extra work. Use the config's theme object (separate light and dark values) only for a colour that is not a token. It applies the dark value under the .dark class and does not follow data-theme="dark".

Examples

Bar

Bars compare a value across categories. The first example on this page has one series. With several, give each a key in the config and a legend.

Work orders closed per month at Bergamo and Brescia.

Line

A line shows a change over time. Hide the dots on a long series and let the tooltip show the value under the pointer.

Share of supplier deliveries on time, rising from 91% in January to 96% in June.

Area

An area adds weight to a line, for a quantity that accumulates, such as stock. Keep the fill at a low opacity.

Pallets in the Bergamo warehouse at the end of each month.

Pie

A pie shows parts of a whole, for up to five parts. The slice colours come from the fill of each data row, and nameKey tells the tooltip and the legend which field names a slice.

Steel and fasteners take 80 of the 103 thousand euros spent this quarter.

Tooltip

ChartTooltip takes ChartTooltipContent as its content. indicator sets the mark beside each value (dot, line or dashed), hideLabel removes the heading and nameKey or labelKey choose the fields to read. The bar example above uses the dashed indicator.

Legend

ChartLegend takes ChartLegendContent as its content. It reads each series' label from the config, so the legend and the tooltip always agree. A chart with a single series needs no legend, since its title or caption names it.

One highlighted series

Grey series with one crimson series says where to look.

Brescia, the site under review, is the only series in crimson.

Accessibility

A chart is a picture of data. Give the reader the data in text too.

KeyAction
TabMoves focus into the chart and shows the tooltip at the first data point.
ArrowRightMoves the tooltip to the next data point. It stops at the last one.
ArrowLeftMoves the tooltip to the previous data point. It stops at the first one.
EnterShows or hides the tooltip at the current point.
EscapeHides the tooltip.

Recharts provides:

  • The accessibility layer: a focusable chart that moves through the data with the arrow keys and shows the tooltip. In Recharts 3 the accessibilityLayer prop is on by default. The examples set it anyway, so the intent stays visible and a later change to the default does not remove it.

You provide:

  • A text alternative. Put the chart in a figure with a figcaption that states the finding, as in "Defects per 1,000 units fell from 14 in January to 6 in April", and add the data as a visually hidden table when the numbers matter.
  • Meaning that does not rest on colour. A legend, direct labels and a tooltip name every series. The ink ramp separates series by lightness, so check that neighbours differ.
  • Axis labels in a size people can read. The chart text is 13px.
  • A static fallback in print and reports: a table of the figures.
Defects per 1,000 units fell from 14 in January to 6 in April.
Defects per 1,000 units by month
MonthDefects
Jan14
Feb11
Mar9
Apr6

Guidelines

When to use

  • To show a trend, a comparison or a share that people read faster as a shape than as numbers.
  • For a summary on a dashboard, with the exact figures one click away.

When not to use

  • For exact values people need to look up. Use a Table.
  • For one number. Show the number in large text, with its change in small text.
  • For more than five series or parts. Group the rest as "Other", or split the chart.
  • For a status of one item. Use the state square with a word, as in Badge.

Content

  • Title the chart with what it measures and the period, and state the finding in the caption.
  • Label axes with units, not with the field name: "Units shipped", not "units".
  • Start bar charts at zero. A line may start elsewhere if the axis says so.
  • Use dates and names in the form of the rest of the page.

Colour

Do

Use the ink ramp, and keep crimson for the one series that matters.

Don’t

Don’t paint bars in crimson at random. Crimson means look here, and it is used up.

API reference

ChartContainer

Renders a div that holds a Recharts ResponsiveContainer, and defines a --color-<key> variable for every config entry that has a colour. It accepts every div prop and the props below. Its aspect ratio is 16 to 9 unless you set one.

PropTypeDefaultDescription
configChartConfigNoneThe label, icon and colour of each series, by key.
childrenReactElementNoneA Recharts chart, such as BarChart or PieChart.
id?stringNoneA stable identifier for the generated colour variables. A generated one is used by default.
initialDimension?{ width: number; height: number }{ width: 320, height: 200 }The size used before the container is measured.
className?stringNoneClasses merged onto the container. Set a minimum height here.

ChartConfig

The type of the config prop: a record from series key to its label and either a color or a theme.

PropTypeDefaultDescription
label?ReactNodeNoneThe name shown in the tooltip and the legend.
icon?ComponentTypeNoneAn icon shown in place of the colour mark.
color?stringNoneOne colour for both modes. Use a token such as var(--chart-1).
theme?{ light: string; dark: string }NoneA colour per mode, used instead of color.

ChartTooltip

The Recharts Tooltip, exported under this name. It accepts every Recharts Tooltip prop.

ChartTooltipContent

The tooltip body, passed as content. It reads labels and colours from the config.

PropTypeDefaultDescription
indicator?"dot" | "line" | "dashed""dot"The mark beside each value.
hideLabel?booleanfalseHides the heading of the tooltip.
hideIndicator?booleanfalseHides the mark beside each value.
nameKey?stringNoneThe data field that names each item, used to look up its config.
labelKey?stringNoneThe field or config key used for the heading.
labelFormatter?(value, payload) => ReactNodeNoneFormats the heading.
formatter?(value, name, item, index, payload) => ReactNodeNoneReplaces the rendering of each row.
color?stringNoneOverrides the colour of the mark.

ChartLegend

The Recharts Legend, exported under this name. It accepts every Recharts Legend prop.

ChartLegendContent

The legend body, passed as content.

PropTypeDefaultDescription
nameKey?stringNoneThe data field that names each item, used to look up its config.
hideIcon?booleanfalseHides the icon or colour mark.
verticalAlign?"top" | "middle" | "bottom""bottom"Sets the spacing for a legend above or below the chart. Only top changes it: middle gets the same spacing as bottom.

ChartStyle

Renders the style element that defines the --color-<key> variables. ChartContainer uses it for you; you do not need to render it yourself.