Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I am developing an application with Flask Backend with ReactJS front. ReactJS app has been developed and bundled with webpack.

Everything works fine with client side rendering which is bundled with webpack.

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

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

I had to send my routes and config to my application via jinja2 template like 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 above js variables are being set to global window object .

But when I am trying to render the component in python, it throws exception for window object ReactRenderingError: react: ReferenceError: window is not defined .

What is the best way to solve this issue ?

share|improve this question
    
Hi ! You use React.renderToString ( or React.renderToStaticMarkup) server side ? – Jean Jun 24 '15 at 15:18

There is no window global when rendering on the server. You can create a fake window, first checking 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.

share|improve this answer
    
lol which file do you mock the fake window? – Anthony Chung Jul 8 '16 at 21:02
    
The closer to the initialization of the app the better, in node when you define something on the global it's available to all files. If your npm start is running a script called index.js, then try to define it in index.js or one of the files that index.js requires. – TigerC10 Aug 16 '16 at 18:02

Just add the following to webpack config:

  // By default, Webpack is set up to target the browser,
  // not a Node environment. Try setting target in your config:
  target: 'node',
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.