Chart instance
Chart factory
Section titled “Chart factory”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") });Arguments
Section titled “Arguments”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.
Throws
Section titled “Throws”| 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." |
Chart instance
Section titled “Chart instance”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
dataandoptionsare required. Callingset()before that with only one of them throws"Both data and options must be provided for the initial render". - On later calls, either
dataoroptionscan be omitted to update only the other one. Callingset()with neither is a no-op. optionsreplaces 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 previousset()call.
// Initial render; both requiredchart.set({ data, options });
// Later; update only the datachart.set({ data: newData });cleanup()
Section titled “cleanup()”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();addHook()
Section titled “addHook()”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.
removeHook()
Section titled “removeHook()”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);