0

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.

2 Answers 2

0

Do a simple check for window.

if (typeof window !== 'undefined') {
    // write your logic here
}
2
  • window is used in a NPM component (Pikaday, Leaflet). I can't make any changes to that. On my side I'm doing a check for window - the variable isServer in the code snippet I posted is the result of this function call export const isServer = !( typeof window !== 'undefined' && window.document && window.document.createElement ); But that's not the problem. The problem is how NOT to load Pikaday component somehow on server but then LOAD it later on the client side. Or at least that's what I think I need to achieve. Commented Jul 26, 2018 at 8:29
  • I made a change to the if condition so the code is clearer. Commented Jul 26, 2018 at 8:35
0

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.