Skip to content

Framework integration

The library has no framework dependency. It renders into whatever container element you give it. Wire it into a component’s lifecycle with three rules, the same three methods from Basic usage:

  1. Create the chart once the container element exists in the DOM, and is empty.
  2. Call set() whenever the data or options change.
  3. Call cleanup() when the component is removed, so the container is empty if it’s ever reused.
import { useEffect, useRef } from "react";
import { BarChart } from "@statistikzh/charts";
import type { BarChartOptions, DataList } from "@statistikzh/charts";
function Chart({ data, options }: { data: DataList; options: BarChartOptions }) {
const containerRef = useRef<HTMLDivElement>(null);
const chartRef = useRef<ReturnType<typeof BarChart>>();
useEffect(() => {
if (!containerRef.current) return;
chartRef.current = BarChart({ el: containerRef.current });
return () => chartRef.current?.cleanup();
}, []);
useEffect(() => {
chartRef.current?.set({ data, options });
}, [data, options]);
return <div ref={containerRef} />;
}
<script setup>
import { onMounted, onUnmounted, ref, watch } from "vue";
import { LineChart } from "@statistikzh/charts";
const props = defineProps(["data", "options"]);
const container = ref(null);
let chart;
onMounted(() => {
chart = LineChart({ el: container.value });
chart.set({ data: props.data, options: props.options });
});
watch([() => props.data, () => props.options], ([data, options]) => {
chart?.set({ data, options });
});
onUnmounted(() => {
chart?.cleanup();
});
</script>
<template>
<div ref="container"></div>
</template>
<script>
import { onMount, onDestroy } from "svelte";
import { BarChart } from "@statistikzh/charts";
export let data;
export let options;
let container;
let chart;
onMount(() => {
chart = BarChart({ el: container });
chart.set({ data, options });
});
$: chart?.set({ data, options });
onDestroy(() => {
chart?.cleanup();
});
</script>
<div bind:this={container}></div>

Lit is what the library’s own components are built with. Create the chart in firstUpdated(), once the element’s shadow or light DOM has rendered, and clean it up in disconnectedCallback().

If your framework destroys and recreates the container element itself, for example behind a conditional block or a changed key, the existing chart instance becomes stale. Create a new chart instance rather than calling set() on it.