react-vega icon indicating copy to clipboard operation
react-vega copied to clipboard

[Question] Does it support server side rendering?

Open ZeRego opened this issue 1 year ago • 1 comments

I want to render in the server a react page that includes a Vega chart. Is this possible?

At the moment the example code only returns an empty div.

<div style="width:100%;height:100%;min-height:300px"/>

Server

const html = renderToStaticMarkup(<VegaViz spec={vegaSpec}/>);

Component

const VegaViz = ({spec}: { spec: vega.Spec }) => {
    return (
        <Vega
            style={{
                width: '100%',
                height: '100%',
                minHeight: 300,
            }}
            spec={spec}
            renderer={'svg'}
        />
    );
};

ZeRego avatar Apr 16 '24 14:04 ZeRego

Rendering a Vega chart on the server-side using React can be a bit tricky because Vega (and Vega-Lite) relies on browser-specific APIs (like the DOM) to render charts. The renderToStaticMarkup function from react-dom/server renders components to static HTML and doesn't execute any client-side code or lifecycle methods, which is why your Vega chart isn't appearing.

However, you can achieve server-side rendering (SSR) by using a workaround that involves pre-rendering the chart on the server and then hydrating it on the client.

jardelva96 avatar Aug 06 '24 00:08 jardelva96

Like @jardelva96 said, vega-embed relies on browser APIs. This library is a thin wrapper around vega-embed so this issue is out of the scope of this library.

JakeAdler avatar Sep 04 '25 01:09 JakeAdler