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.
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.
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.
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.
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.
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()); };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With