node.jsreactjsleafletserver-side-renderingpikaday

How to use components that use `window` reference in React with server-side rendering?


An example of such component is Pikaday (react-pikaday) that contains in its code this line

hasEventListeners = !!window.addEventListener

but window is not defined on server so when I run the code it throws an error ReferenceError: window is not defined.

I tried to solve this issue by conditionally import Pikady component, something along these lines:

let Pikaday;
if (typeof window !== 'undefined' && window.document && window.document.createElement) {
    import('./Pikaday').then(P => {
        Pikaday = P.default;
    });
}

In such a case it doesn't throw an error because the component is not loaded but I presumed that the initial HTML sent from server would not contain this component and then it would somehow "switch" to JS code on client side and the component would load. But this doesn't happen. I'm new to server-side rendering in general so I'm getting a bit lost.

How can I solve this? I have the same problem with Leaflet library that also contains window in its code.


Solution

  • I eventually used this fork of Pikaday that introduces several small changes to check for window availability:

    https://github.com/everdimension/Pikaday

    I don't think there was any other way than edit the plugin itself.