Bolboa Bolboa - 3 months ago 24
React JSX Question

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

The following node.js code is rendering my

App
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...

render(){

console.log(this.props.exists);
...
...


When I run this through my terminal, the console prints out
true
. However, in my browser terminal I get
undefined
, 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?

EDIT

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')
window.data =!{JSON.stringify(errorExist)};


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

if (window.data) {
return (
<Register />

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

);
}


But I get error
window
and
data
are not defined
.

Answer

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.

node.js

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