piRstone piRstone - 29 days ago 17
Javascript Question

React Recharts - ReferenceError: document is not defined

I have a problem with React server side rendering and Recharts.
When I pass data via props to my chart, reload my server and refresh my page, I get an error :

ReferenceError: document is not defined
at Text.calculateWordWidths (/Users/piRstone/Documents/node/dashboard/node_modules/recharts/lib/component/Text.js:101:26)
at Text.updateWordsByLines (/Users/piRstone/Documents/node/dashboard/node_modules/recharts/lib/component/Text.js:81:43)
at Text.componentWillMount (/Users/piRstone/Documents/node/dashboard/node_modules/recharts/lib/component/Text.js:67:12)
[...]


Even if I pass static data from a const in the chart's file it still doesn't works.

When I tried Recharts without server side rendering, everything worked fine but as soon as I set SSR, I got this error.

I tried to remove the
data={this.props.data}
from the chart declaration so my page displayed correctly (without chart of course) but if if reset this, I still get this error.

I thought it was a bug as said in the issue on Github (probably resolved but apparently not)

Answer

I found a solution that works. I use Redux in my project, so I use the state to return or not my chart.

render() {
    if (browser) {
        return (
            <div>
                <AreaChart width={630} height={300} data={views.views} margin={{top: 5, right: 30, left: 20, bottom: 5}}>
                    // Code
                </AreaChart>
            </div>
        );
    } else {
        return null;
    }
}

By default, the browser state is false. I dispatch an action to change it state when the component mounts:

componentDidMount() {
    const {dispatch} = this.props;
    if (typeof(document) != "undefined") {
        dispatch(setOnBrowser(true))
    }
}

As the server has already sent the data via the props, the component has just to re-render and it works for me.

Comments