Building blocks
Hooks and providers
BarChart and LineChart read their number formats from a provider, and a mark of your own can do the same. This page covers ChartsProvider, which sets the locale and currency for everything inside it, and the three hooks you need to draw something the library does not: useChart, useFormat and useRegisterPoints.
ChartsProvider #
Put ChartsProvider once near the top of the page. locale is a BCP 47 tag and currency an ISO 4217 code. Every chart, Stat, Meter and axis below it formats numbers, dates and currency that way, so the same data reads naturally for each audience. Without a provider the defaults are en-US and USD.
| Month | Revenue |
|---|---|
| Jan | 12.400 € |
| Feb | 13.850 € |
| Mar | 15.200 € |
| Apr | 14.700 € |
| May | 16.900 € |
| Jun | 18.350 € |
- Revenue
- Cost
| Month | Revenue | Cost |
|---|---|---|
| Jan | 12.400 € | 9.100 € |
| Feb | 13.850 € | 9.600 € |
| Mar | 15.200 € | 10.400 € |
| Apr | 14.700 € | 10.100 € |
| May | 16.900 € | 11.200 € |
| Jun | 18.350 € | 11.900 € |
import { BarChart, ChartsProvider, Legend, LineChart, Stat } from 'tally-charts'
import type { ExampleMeta } from '../types'
export const meta = {
id: 'hooks-and-providers/provider-locale',
title: 'German locale for every chart on the page',
rscSafe: true,
} satisfies ExampleMeta
const months = [
{ month: 'Jan', revenue: 12400, cost: 9100 },
{ month: 'Feb', revenue: 13850, cost: 9600 },
{ month: 'Mar', revenue: 15200, cost: 10400 },
{ month: 'Apr', revenue: 14700, cost: 10100 },
{ month: 'May', revenue: 16900, cost: 11200 },
{ month: 'Jun', revenue: 18350, cost: 11900 },
]
// One provider sets the locale and currency for everything inside it. Props stay serializable
// (no functions), so the page can render this in a Server Component.
export default function ProviderLocale() {
return (
<ChartsProvider locale="de-DE" currency="EUR">
<div style={{ display: 'grid', gap: '1.5rem' }}>
{/* md, not the default lg: the 72 px value is 314 px wide in linux fonts and overflows a 320 px screen. */}
<Stat
size="md"
label="Revenue in June"
value={18350}
format="currency"
caption="Jan to Jun: 91.400 €"
/>
<BarChart
data={months}
x="month"
y="revenue"
domain={[0, 20000]}
format="currency"
height={240}
title="Revenue by month, in euros"
description="Revenue grew from 12.400 € in January to 18.350 € in June."
/>
<div>
<Legend
shape="line"
items={[
{ label: 'Revenue', tone: 'accent' },
{ label: 'Cost', tone: 'neutral' },
]}
/>
<LineChart
data={months}
x="month"
series={[
{ id: 'revenue', label: 'Revenue', value: 'revenue' },
{ id: 'cost', label: 'Cost', value: 'cost', tone: 'neutral' },
]}
format="currency"
height={240}
title="Revenue and cost by month, in euros"
description="Revenue stayed above cost every month, and the gap widened."
/>
</div>
</div>
</ChartsProvider>
)
}
The Stat and both charts share one provider: thousands are separated with a dot, the decimal separator is a comma and the euro sign follows the number. Nothing is passed to the charts except format="currency". The props are plain values, so this example also renders in a Server Component; see Getting started for the charts used here and LineChart for series.
Translating the built-in text #
locale changes numbers and dates; messages changes the words the charts speak on their own: "No data", the keyboard hint, the "1 of 6" position, target text, the column headers of the hidden data table and the default Runway status. Pass an object of plain strings, with {placeholders} where a value goes. Any key you leave out keeps its English default, and a key set to undefined does too. The strings are not functions, so a Server Component can pass them to the provider.
import { type ChartMessages, ChartsProvider, Meter, RankedBars } from 'tally-charts'
import type { ExampleMeta } from '../types'
export const meta = {
id: 'hooks-and-providers/polish-messages',
title: 'Planned hours by technician, in Polish',
rscSafe: true,
} satisfies ExampleMeta
const plan = [
{ name: 'Tomasz Brodzki', hours: 62, jobs: '9 zleceń' },
{ name: 'Dana Ostrowska', hours: 54, jobs: '8 zleceń' },
{ name: 'Sebastian Patel', hours: 47, jobs: '6 zleceń' },
{ name: 'Priya Nowak', hours: 31, jobs: '4 zlecenia' },
]
// Keys left out keep their English default. Strings take {placeholders}, not functions, so the
// object can cross from a Server Component to the provider. In a Client Component, define it
// outside the component (or in useMemo): a new object on every render re-renders every chart
// below the provider.
const pl: Partial<ChartMessages> = {
noData: 'Brak danych',
keyboardHint:
'Strzałki przesuwają między punktami, Home i End skaczą na początek i na koniec, Escape czyści.',
position: '{index} z {total}',
target: 'cel {value}',
targetLabel: 'Cel {value}',
headerItem: 'Pozycja',
headerValue: 'Wartość',
headerRankedDetails: 'Szczegóły',
}
export default function PolishMessages() {
return (
<ChartsProvider locale="pl-PL" messages={pl}>
<div style={{ display: 'grid', gap: '1.5rem' }}>
<RankedBars
data={plan}
label="name"
value="hours"
meta="jobs"
format="hours"
title="Planowane godziny według technika"
description="Tomasz Brodzki ma zaplanowane 62 godziny przy 9 zleceniach, Priya Nowak 31 godzin przy 4."
/>
<Meter label="Plan sprzedaży" value={68} max={100} target={80} format="percent" />
</div>
</ChartsProvider>
)
}
The order of precedence is the prop of one chart (empty, keyboardHint, targetLabel, totalLabel, dataTable.columns), then the provider's messages, then English. A column header taken from a string accessor (y="grossMargin" reads "Gross margin") stays the field name; messages supplies the header only when the accessor is a function or the chart names the column itself. A nested provider without messages inherits its parent's, so <ChartsProvider currency="EUR"> inside a translated provider keeps the translation. One with messages replaces them instead of merging: any key it leaves out goes back to English, not to the parent's text. locale and currency don't inherit: each provider sets its own, with en-US and USD as the defaults.
The provider remembers your object by identity. An inline object, messages={{ noData: '…' }} in a Client Component, is a new object on every render of the parent, so every chart under it renders again. Define the object outside the component or wrap it in useMemo. In a Server Component this does not matter.
The unit suffixes of the pts and hours format presets are not messages; use a custom format function for those units in another language (see Formatting). The wording of the English defaults below is not public API and can change in a minor release; the keys are.
| Key | English default | Where it is used |
|---|---|---|
noData | No data | An empty chart, bar or meter. Also the cell text for a missing heatmap value. |
noValue | no value | A table cell with nothing in it, read by screen readers next to the dash. |
keyboardHint | Use arrow keys to move between points, Home and End for first and last, Escape to clear. | Read when a chart takes keyboard focus. An empty string removes the hint. |
keyboardHintSelect | Press Enter to select. | Appended to keyboardHint, after one space, when the point can be selected. |
position | {index} of {total} | The live-region position of a point. Placeholders: {index}, {total}. |
target | target {value} | A target in a spoken value, such as "40, target 50". Placeholder: {value}. |
targetLabel | Target {value} | The default text under a Meter's target tick. Placeholder: {value}. |
now | Now | The Now line of a RunwayChart. |
total | Total | The total column and row of a Heatmap, and the end row of a WaterfallChart. |
headerItem | Item | A column header of a chart's hidden data table. A header taken from a string accessor keeps the field name. |
headerValue | Value | A data-table column header. |
headerCategory | Category | A data-table column header. |
headerDate | Date | A data-table column header. |
headerPeriod | Period | A data-table column header. |
headerGroup | Group | A data-table column header. |
headerRankedDetails | Details | The data-table column of a RankedBars meta. |
headerColumn | Column | A data-table column header. |
headerChange | Change | A data-table column header. |
headerTotal | Total | A data-table column header. |
headerPlan | Plan | A data-table column header. |
headerActual | Actual | A data-table column header. |
headerDifference | Difference | The ComparisonBars data-table column of plan minus actual. |
headerRange | Range | The data-table column of a LineChart band. |
headerRow | Row | The row name of a Heatmap that has no label. |
headerName | Name | A RunwayChart or ScatterChart data-table column header. |
headerX | X | The name of a ScatterChart x measure that has no xLabel and no field name. |
headerY | Y | As headerX, for y. |
headerSize | Size | As headerX, for size. |
headerRunwayDetail | Detail | The data-table column of a RunwayChart row's sublabel. |
headerRunsOut | Runs out | A RunwayChart data-table column header. |
headerResets | Resets | A RunwayChart data-table column header. |
headerProjectedAtReset | Projected at reset | A RunwayChart data-table column header. |
headerStatus | Status | A RunwayChart data-table column header. |
statusDisconnected | Disconnected | Default status of a RunwayChart row whose source is disconnected. |
statusNoForecast | No forecast | Default status of a RunwayChart row without a forecast. |
statusRunsOut | Runs out {date} | Default status line of a RunwayChart row. Placeholder: {date}. |
statusAtReset | ~{percent}% at reset | Default status line when a RunwayChart row does not run out. Placeholder: {percent}. |
statusResets | Resets {date} | Default status line of a RunwayChart row's reset. Placeholder: {date}. |
legendProjectedUse | Projected use | RunwayChart legend. |
legendUnderShare | under {shares}% | RunwayChart legend, after the shades. Placeholder: {shares}, the level edges as percentages, such as "25, 50, 75, 100". |
legendRunsOut | Runs out | RunwayChart legend. |
legendLocked | Locked until reset | RunwayChart legend. |
legendReset | Reset | RunwayChart legend. |
legendNoForecast | New window, no forecast | RunwayChart legend. |
onPlan | On plan | The change a ComparisonBars row shows when actual is within the tolerance. |
planActual | {label}, plan {plan}, actual {actual}, {delta} | A ComparisonBars row read aloud. Placeholders: {label}, {plan}, {actual}, {delta}. |
waterfallStep | {label}, {text}, running total {total} | A WaterfallChart step read aloud. Placeholders: {label}, {text}, {total}. |
chartRole | chart | What a screen reader calls an interactive chart (aria-roledescription). |
runningTotalLabel | total | The label of the running total in a WaterfallChart tooltip. |
peak | Peak | The first line of a WaffleColumns callout. |
binAll | All values | The default Heatmap legend label when there are no breaks. |
binUnder | Under {value} | The lowest Heatmap legend bin. Placeholder: {value}. |
binRange | {from} to {to} | A middle Heatmap legend bin. Placeholders: {from}, {to}. |
binOver | {value} and up | The highest Heatmap legend bin. Placeholder: {value}. |
valueAgainst | {value} against {reference} | A RangeMeter's value against its reference, read aloud. Placeholders: {value}, {reference}. |
valueAbove | above {max} | A ZoneMeter value above its maximum. Placeholder: {max}. |
valueBelow | below {min} | A ZoneMeter value below its minimum. Placeholder: {min}. |
resetMark | reset | The label next to the reset tick of a RunwayChart row. |
heatmapName | Heatmap | The accessible name of a scrolling Heatmap that has no title. |
deltaUp | Up | Read before a Delta's value when it went up. |
deltaDown | Down | Read before a Delta's value when it went down. |
deltaFlat | No change | Read before a Delta's value when it did not change. |
Custom marks #
When none of the building blocks in Composition draws what you need, write a component and put it inside Chart. useChart() returns the size, the margins, the data, the number formatter, the active point and the x and y scales (narrow them on kind: 'linear', 'band', 'point' or 'time'), y2 when the chart has a second axis it can use (undefined otherwise), useFormat() returns formatters in the provider's locale, and useRegisterPoints() tells the chart where your points are.
'use client'
import { useMemo } from 'react'
import {
Axis,
Chart,
type ChartPoint,
ChartsProvider,
Grid,
NearestPointer,
Tooltip,
useChart,
useFormat,
useRegisterPoints,
} from 'tally-charts'
import type { ExampleMeta } from '../types'
export const meta = {
id: 'hooks-and-providers/custom-mark',
title: 'Average order value by month, as lollipops',
rscSafe: false,
} satisfies ExampleMeta
interface Order {
month: string
value: number
}
const orders: Order[] = [
{ month: 'Jan', value: 48 },
{ month: 'Feb', value: 52 },
{ month: 'Mar', value: 61 },
{ month: 'Apr', value: 57 },
{ month: 'May', value: 68 },
{ month: 'Jun', value: 74 },
]
// A custom mark is a component inside <Chart>. Three hooks do the work:
// - useChart() gives the scales and the size, so the mark can place itself;
// - useFormat() formats numbers in the ChartsProvider's locale and currency;
// - useRegisterPoints() hands the chart the mark's points, so hover, the arrow keys, the tooltip
// and the screen-reader announcements work on it.
// Hooks cannot run in a Server Component, hence 'use client'.
function Lollipops({ rows }: { rows: readonly Order[] }) {
const { x, y, activeId } = useChart()
const { create } = useFormat()
// Memoize: the chart re-registers points whenever the array identity changes.
const points = useMemo<ChartPoint<Order>[]>(() => {
if (x.kind !== 'point' || y.kind !== 'linear') return []
const money = create({ preset: 'currency', digits: 0 })
return rows.flatMap((row, index) => {
const px = x.scale(row.month)
if (px === undefined) return []
const text = money(row.value)
return [
{
id: row.month,
index,
datum: row,
x: px,
y: y.scale(row.value),
label: `${row.month}, ${text}`,
segments: [{ value: row.month }, { value: text, tone: 'accent' as const }],
},
]
})
}, [rows, x, y, create])
useRegisterPoints(points)
if (x.kind !== 'point' || y.kind !== 'linear') return null
const base = y.scale(0)
return (
<g>
{points.map((p) => {
const active = p.id === activeId
return (
<g key={p.id}>
<line x1={p.x} x2={p.x} y1={base} y2={p.y} stroke="var(--ch-accent)" strokeWidth={2} />
<circle
cx={p.x}
cy={p.y}
r={active ? 7 : 5}
fill="var(--ch-accent)"
stroke="var(--ch-surface)"
strokeWidth={2}
/>
</g>
)
})}
</g>
)
}
export default function CustomMark() {
return (
<ChartsProvider locale="en-GB" currency="GBP">
<Chart
data={orders}
x={{ type: 'point', field: 'month' }}
y={{ field: 'value', domain: [0, 80] }}
margin={{ left: 44, right: 24 }}
height={260}
title={meta.title}
description="Average order value rose from £48 in January to £74 in June."
>
<Grid ticks={4} />
<Lollipops rows={orders} />
<Axis side="left" ticks={4} format={{ preset: 'currency', digits: 0 }} />
<Axis side="bottom" />
<NearestPointer axis="x" radius={32} />
<Tooltip />
</Chart>
</ChartsProvider>
)
}
Lollipops are not a built-in mark. Lollipops reads the scales with useChart(), labels each point with a formatter from useFormat(), and registers the points. That registration is what makes NearestPointer find them under the pointer, Tooltip show them and the arrow keys walk them. Focus the chart and press Home to hear the first one.
Several React roots on one page #
Pattern ids, for hatching and gradients, come from React's useId, which is only unique within one root. When charts render in separate roots (islands, micro-frontends), two charts can end up with the same pattern id. Give each chart its own chartId. Chart, the high-level charts and Heatmap take it.
<BarChart chartId="margin-chart" data={weeks} x="week" y="margin" title="Margin by week" />Props #
| Name | Type | Default | Required | Description |
|---|---|---|---|---|
children | ReactNode | — | No | — |
currency | string | — | No | — |
locale | string | — | No | — |
messages | Partial<ChartMessages> | — | No | Built-in text such as "No data" or the keyboard hint, in your language. Keys left out keep their English default. A nested provider without this prop inherits its parent's messages; one with it replaces them, and any key it leaves out goes back to English, not to the parent's text. Memoised by object identity, so an inline object re-renders every chart under it on each render of the parent: hoist it or wrap it in |
useChart has no parameters.
Returns ChartContextValue
useFormat has no parameters.
Returns UseFormatResult
| Parameter | Type | Default | Required | Description |
|---|---|---|---|---|
points | readonly ChartPoint[] | — | Yes | — |
Returns void