nettofarah/react-flexible-switch

Server Side Rendering Support

Opened this issue · 7 comments

When using this component with server side rendering, this error occured:

ReferenceError: window is not defined

This is when you check about touch device:

this.isTouchDevice = window['ontouchstart'] !== undefined;

Currently, i just add this:

if (window !== undefined)
    this.isTouchDevice = window['ontouchstart'] !== undefined;
else
    this.isTouchDevice = false;

Not sure this is the good solution, but if it can help...

hey, @littlepsylo.
Thank you for catching this.
I'm not sure what the implications would be if the user was actually on a mobile device.

However, I think this might be good enough. I'm assuming react would try to re-render the component on the client side when it is done rendering, right?

Are you seeing any weirdness with mobile devices?

Thank you!

Yes, it's definitly not a good solution and finally i used a trick... an ugly one :(

For making this work, I'm forcing react to render client side again with your component, and without on the server, but this is not very comfortable and optimized. The problem is when rendering on the server, window does not exist and this just crash the app in both desktop or touch devices.

Let's try and change it to something like:
this.isTouchDevice = window && window['ontouchstart'] !== undefined;

This might be enough to get everything working I think.

Ok thanks, i try this tonight.

hey, @littlepsylo. Do you still wanna try to work on this?

Hi ! Sorry for my late return, too much work...

I have a project that use version 0.3.4, that i have to resume soon, so i could look at it at the same time.

And for information, during a demo of this project, when trying to use a switch with my mouse on a touch screen, only touch working not click. I will re-test that too.

Your previous solution still does not work, window isn't defined...

But i've found a working fix by removing

this.isTouchDevice = window['ontouchstart'] !== undefined;

And updating addListener and removeListener by replacing

if (this.isTouchDevice) {

with

if (window['ontouchstart'] !== undefined) {

And now it's work with SSR.

This is make sense because these 2 methods are not called during server side rendering but when the component is mounted or unmounted. This only happens on browser, not on server.