Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
13
rated 0 times [  14] [ 1]  / answers: 1 / hits: 72386  / 8 Years ago, mon, august 15, 2016, 12:00:00

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.


More From » reactjs

 Answers
31

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.




Note: Initially, when you start up your project its going to render out a complete string of your DOM (at this point it will not know about window because it is server side, but then re-render with the client-side code to which your window object will be available!




There is a workaround that I am using in this case. This is what I have for my webpack plugin:



new webpack.DefinePlugin({
'process.env.NODE_ENV': isDevelopment ? 'development' : 'production',
'process.env.BROWSER': JSON.stringify(true),
__DEV__: isDevelopment
}),


So I use process.env.BROWSER to my advantage because it will be defined as undefined if it is server side, and it will be true 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:



const mySpecialWindowFunction = () => {

/* START HACK */
if (!process.env.BROWSER) {
global.window = {}; // Temporarily define window for server-side
}
/* END HACK */

return /msie [6-9]b/.test(window.navigator.userAgent.toLowerCase());
};


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.




Also Note: Don't worry about setting window as an empty object, it will be back to normal once the client-side finishes rendering.



[#61036] Thursday, August 11, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
laytonlamontm

Total Points: 745
Total Questions: 130
Total Answers: 130

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
;