Skip to content

Chart instance

Signature: (args: ChartArgs) => { set, cleanup, addHook, removeHook }

BarChart and LineChart are chart factories. Calling one creates a chart instance. There is no exported type for the returned instance; its four methods are documented individually below.

const chart = BarChart({ el: document.getElementById("chart") });

Type: HTMLElement
Required

The container element the chart renders into. The element must be empty. The factory creates one child element inside it to hold the chart.

Condition Message
el is not provided "No element provided"
el already has children "Element is not empty. If you're replacing a chart, call cleanup() first or if you're updating, use the set() method."

The object returned by a chart factory. It exposes four methods.

Type: (args: { data?: DataList; options?: ChartOptions }) => void

ChartOptions is LineChartOptions | BarChartOptions. In practice, options must match the options type of the chart factory that created the instance; a BarChart instance only accepts BarChartOptions.

Sets the data and options for the chart.

  • On the first call, both data and options are required. Calling set() before that with only one of them throws "Both data and options must be provided for the initial render".
  • On later calls, either data or options can be omitted to update only the other one. Calling set() with neither is a no-op.
  • options replaces the previous options; it is not merged with them. It is merged only with the library’s internal defaults. Omitted options fall back to those defaults, not to the values from a previous set() call.
// Initial render; both required
chart.set({ data, options });
// Later; update only the data
chart.set({ data: newData });

Type: () => void

Removes the chart from the DOM and releases its resources. After cleanup(), el is empty again and can be passed to a chart factory once more.

chart.cleanup();

Type: <T extends HookType>(type: T, hook: HookDefinitions[T]) => () => void

Registers a hook function and returns a function that unregisters it. See Hooks for the available hook types and a note on the non-exported type names used here.

const unsubscribe = chart.addHook("tooltip:items", (state) => {
return [];
});
unsubscribe();

Registering the same function reference twice for the same hook type has no additional effect; it runs once.

Type: <T extends HookType>(type: T, hook: HookDefinitions[T]) => void

Unregisters a previously added hook function. Equivalent to calling the function returned by addHook().

chart.removeHook("tooltip:items", myHookFunction);