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.
When doing server-side-rendering, global like
window
,document
will be undefined. And if you want to do it in isomorphic way, you have to test what environment is when rendering componets.https://github.com/DavidWells/isomorphic-react-example
many example codes can be found on github, the link above is one of them, hope it can be helpful.
Another solution I found, is that you can assign your state variables with your 'window variables' in the 'componentDidMount' event, and in the 'render' method you can test if the state variables you want are null or undefined then return null, until the 'componentDidMount' finish.
I tried setting it in my constants as a global import:
In this case it returns window or global object depending on weather your running it on client application or server.
Now you need to import this constant wherever you want to make use of window object.
Ex:
Here is a npm library which can handle window, document and global object for you: Global.
Then you can safely write:
If you're doing server side rendering, there's a good chance that the global window object is going to be undefined because that is only something the client will understand.
There is a workaround that I am using in this case. This is what I have for my webpack plugin:
So I use
process.env.BROWSER
to my advantage because it will be defined asundefined
if it is server side, and it will betrue
if the client side is done rendering.Since everything just stops working when there isn't a window object on the server side we can add this:
That way, your console won't scream at you and doesn't stop the server side rendering, to which you can now carry on with your glorious day! Although I have to admit that this is a bit Hacky, but it gets the job done because all we want to do is let the server side render out the initial DOM string and then let the client-side take over.
I've been using ReactJS.NET targeting build to client and server, and got the same problem.
The solution is to set
output.globalObject
to'this'
.Without that option set, it's falling back to
window
which is working on client-only code.