Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JS Server side issue - window not found

Hi I'm trying to use react-rte in my reactJS project. I have server side rendering and every time I want to use this package I get:

return /msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase());                                ^ ReferenceError: window is not defined 

I guess the problem might be with isomorphic-tools but I don't know how to defer importing package to the client where window is going to be defined already.

like image 436
Jan Omacka Avatar asked Aug 15 '16 08:08

Jan Omacka


People also ask

How do you fix ReferenceError window is not defined?

To solve the "ReferenceError: window is not defined" error, make sure to only use the window global variable on the browser. The variable represents a window containing a DOM document and can't be used on the server side (e.g. in Node. js). If you need to define global variables in Node.

How do you solve next JS window is not defined?

An easy solution to resolve this issue is to rely on the useEffect , conveniently hooks aren't run when doing server-side rendering. Wrapping the usage of window inside a useEffect that is triggered on mount means the server will never execute it and the client will execute it after hydration.

How do I use Windows server-side rendering?

window is not defined on the server, so you can't use it during the render of a component being SSR'd. During a component render, use the useIsSsr hook. If outside of a component render, then directly check typeof window === "undefined" to see if you're on the server or the browser.

Can you use React for server side?

Server-side rendering with JavaScript libraries like React is where the server returns a ready to render HTML page and the JS scripts required to make the page interactive. The HTML is rendered immediately with all the static elements.


1 Answers

Here is a npm library which can handle window, document and global object for you: Global.

Then you can safely write:

import window from 'global'  const mySpecialWindowFunction = () => {     return /msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase()); }; 
like image 103
Natrezim Avatar answered Sep 30 '22 19:09

Natrezim