How to integrate @observablehq/plot in Svelte?
Below is the code, currently working for me, is there a better way to integrate?
<script>
import * as Plot from "@observablehq/plot";
export function myplot(node) {
node.appendChild(
Plot.plot({x: {domain: [100, 0]}, grid: true})
)
}
</script>
<div use:myplot></div>
For external components and libraries you have to do something like this. That is a reasonable approach; you can encapsulate the integration in a separate component to make its usage as convenient as you want.
E.g. the most basic approach is to expose all the options as a component property:
<script>
import * as Plot from "@observablehq/plot";
export let options;
function myplot(node) {
node.appendChild(
Plot.plot(options)
)
}
</script>
{#key options}
<div use:myplot {...$$restProps}></div>
{/key}
The {#key}
block makes the plot re-render when the options
change.
Usage:
<script>
import Plot from './Plot.svelte'
</script>
<Plot options={{ x: { domain: [100, 0] }, grid: true }} />
If you need events and other interactivity that can be exposed as needed.