christofr christofr - 1 month ago 30
React JSX Question

Render isomorphic React component which requires window object

I have an isomorphic React application, with components being rendered on the server-side. I wish to use a 3rd party React component: (GraphiQL), and am rendering as such:

var GraphiQLComponent = React.createElement(GraphiQL, { fetcher: graphQLFetcher}, "");

router.get('/graphiql', function (req, res) {
res.send(ReactDOMServer.renderToString(GraphiQLComponent));
});


However, this component uses the window object:
window.localStorage
and
window.addEventListener
, and when I try to load the page in the browser, I get the error:

ReferenceError: window is not defined


Can I render React components which use the window object, on the server? If so, what do I need to do to resolve this error?

Answer

Don't use libraries that depend on window in your components. or Only use these libraries in componentDidMount and exclude them for prerendering (make sure your component don't render different in prerendering or it doesn't work).

I figured I shouldn’t import the library outside the class definition, but instead require it in the componentDidMount method or a called method thereof.

So, instead of:

...
import MyWindowDependentLibrary from 'path/to/library';
...
export default class MyClass extends React.Component {
    ...
    componentDidMount() { MyWindowDependentLibrary.doWork(); }
    ...
}

I did:

// removed import
...
export default class MyClass extends React.Component {
    ...
    componentDidMount() {
        const MyWindowDependentLibrary = require( 'path/to/library' );
        MyWindowDependentLibrary.doWork();
    }
    ...
}
Comments