A lightweight React wrapper around vega-embed
npm i react-vega vega-embed vega-liteIf you need to use Vega (not Vega-Lite), you will also need to install vega.
npm i vegaimport { VegaEmbed } from "react-vega";
function Component() {
return <VegaEmbed spec={spec} options={options} />;
}or
import { useVegaEmbed } from "react-vega";
function Component() {
const ref = React.useRef<HTMLDivElement>(null);
const result = useVegaEmbed({ ref, spec, options });
return <div ref={ref} />;
}| Prop | Type | Default | Notes |
|---|---|---|---|
spec (required) |
VisualizationSpec | string |
— | Inline spec or URL. Accepts both Vega & Vega-Lite. |
options |
EmbedOptions |
{} |
Passed directly to embed(). |
onEmbed |
(result: Result) => void |
— | Called once embed() resolves. See Result for details. |
onError |
(err: unknown) => void |
— | Called if embed() rejects. |
...divProps |
React.HTMLAttributes<HTMLDivElement> |
— | Forwarded to the <div> element used for embedding. |
| ref | React.Ref<HTMLDivElement> |
— | Pass a ref to the <div> element used for embedding. |
type UseVegaEmbedParams = {
ref: React.RefObject<HTMLDivElement>;
spec: VisualizationSpec | string;
options?: EmbedOptions;
onEmbed?: (r: Result) => void;
onError?: (e: unknown) => void;
};
const result: Result | null = useVegaEmbed(params);Returns the current Result (or null while loading).
Important Changes to spec or options will cause the view to be torn down and re-embedded. If you need to update the view without re-embedding, use the View API. Refer to the Recipes section for common use cases.
See storybook for live examples.
const embed = useVegaEmbed({ ref, spec, options: { mode: "vega-lite" } });
function randomize(data) {
if (!embed) return;
embed.view
.data("values", values) // mutate dataset
.runAsync();
}
return (
<>
<button onClick={randomize}>Randomize</button>
<div ref={ref} />
</>
);const embed = useVegaEmbed({
ref,
spec,
});
const changeDimensions = (width: number, height: number) => {
if (!embed) return;
embed.view.width(width).height(height).runAsync();
};const embed = useVegaEmbed({
ref,
spec,
});
useEffect(() => {
if (!embed) return;
const listener = (signal, data) => {
console.log(signal, data);
};
embed.view.addSignalListener("signal", listener);
return () => {
embed.view.removeSignalListener("signal", listener);
};
}, [embed]);For more information see the documentation for vega-embed and the vega View API.
npm inpm run dev– run the storybooknpm run test– run the test suite.