Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass prop server side react

I am using node js to render my react component...

var express = require('express');
var router = express.Router();

var React = require('react');
var reactDom = require('react-dom/server');
var App = React.createFactory(require('../components/index'));

router.get('/', function(req,res) {
    var reactHtml = reactDom.renderToString(App({exists: false}));
    res.render('../../tutorHub/views/index.jade', {reactOutput: reactHtml});
});
module.exports = router;

I am trying to pass a prop, exists: false, to the component.

But in my actual component when I try to console.log...

render(){

    console.log(this.props.exists);
        return (
            <Register />
        );
}

I get undefined rather than true.

How can I fix this? Is this because the browser is re-rendering the page?

like image 477
buydadip Avatar asked Sep 17 '25 14:09

buydadip


1 Answers

The reason is on your client-side, React will render your App component one more time. This time, React will re-render which components are different from server-rendered components. It will refresh your props.exists to undefined because you don't pass anything to App component in your client-side code. There are some techniques to solve it. One way is that in your client-side code, you request exists from the server and pass it to your App component before rendering your application.

like image 128
Phi Nguyen Avatar answered Sep 19 '25 04:09

Phi Nguyen