Managing a window object in an isomorphic application using ReactJS and Flask Python

I am developing an application with Flask Backend with a ReactJS frontend. ReactJS was developed and bundled with webpack.

Everything works fine with client-side rendering, which is related to webpack .

Now I am trying to add python-react server side rendering.

But the problem is that I have to share some variables with my ReactJS application through the Jinja2 template in the base index.html template which has the reactjs root component node <div id='react-node'></div> .

I had to send my routes and config to my application using the jinja2 template as shown below,

 //index.html <!doctype html> <html> ... ... <script type='text/javascript'> var STATIC_IMAGE_ROOT = "{{ url_for('static', filename='img/') }}"; var ROUTES = { ... }; ... </script> </html> 

All the js variables listed above are set to the global window object.

But when I try to display the component in python, it throws an exception for the window object ReactRenderingError: react: ReferenceError: window is not defined .

What is the best way to solve this problem?

+7
flask reactjs webpack isomorphic-javascript serverside-javascript
source share
2 answers

There is no global window on the server during rendering. You can create a fake window by first checking to see if the window exists:

 if (typeof(window) == 'undefined'){ global.window = new Object(); } 

Alternatively, you can use jsdom or a similar library to create a fake DOM.

+6
source share

Just add the following to your webpack configuration:

  // By default, Webpack is set up to target the browser, // not a Node environment. Try setting target in your config: target: 'node', 
+1
source share

All Articles