Bolboa Bolboa - 1 year ago 99
React JSX Question

passing prop server-side is not being rendered client-side

The following node.js code is rendering my

component with a prop...

var reactHtml = reactDom.renderToString(App({exists: true}));
res.render('../../tutorHub/views/index.jade', {reactOutput: reactHtml});

And this component is caught by my jade file as so...

#app != reactOutput

Now in the component itself, I'm checking to see if the prop is rendered...



When I run this through my terminal, the console prints out
. However, in my browser terminal I get
, meaning react is re-rendering the component on the client side after the prop is set.

I am desperately trying to find a fix to this, I do not want to have to restructure my entire website. Can someone help me fix this?

Do I need to prevent the re-rendering somehow?


So in my node.js file I did the following...

var reactHtml = reactDom.renderToString(App({}));
res.render('../../tutorHub/views/index.jade', {reactOutput: reactHtml, errorExist:true});

In my jade file I did the following...

#app != reactOutput

script(type='text/javascript') =!{JSON.stringify(errorExist)};

But now I tried to retrieve the data in my component...

if ( {
return (
<Register />

else {
return (
<Index event={this.handleClick.bind(this)} />


But I get error
are not defined

Answer Source

Lets call {exists: true} the initial state.

1. On the server: Serialize the initial state using JSON.stringify and store it in the jade template.


var reactHtml = reactDom.renderToString(App({exists: true}));
res.render('../../tutorHub/views/index.jade', {
  reactOutput: reactHtml, 
  initialState: JSON.stringify({exists: true})

jade file

#app != reactOutput

#initialState =! initialState

2. On the client: Get the initial state from the DOM and deserialize it using JSON.parse in the getInitialState lifecycle method of the App react component

App react component

getInitialState() {
  return JSON.parse(document.getElementById('initialState').innerHTML)
  1. The exists boolean is now accessible in the App components state through this.state.exists
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download