简体   繁体   中英

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?

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();
    }
    ...
}

Yes you can!

Just do not run that piece of code until window is defined! I also imagine you could use those functions in a componentDidMount() lifecycle function.

if (window !== 'undefined') {
    // do your window required stuff
}

I've used this multiple times in components being rendered server-side, and it works like a charm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM