Learner
Learner

Reputation: 2339

How to pass data in server side rendering to reactjs component from node

I am very new to reactJs and just started to learn the features of reactJS. I am trying to figure out a way to pass the value from nodeJS to reactJS via server side rendering concept.

In the below example, I was able to define a react component and add it in server and render it in UI but I am not sure how to pass the data to the component that can be used inside the component render function.

client.js

var React=require('react');
var ReactDOM=require('react-dom');
var Component=require('./Component.jsx');


ReactDOM.render(
    React.createElement(Component),document
);

Component.jsx

var React=require('react'),
Request=require('superagent')


module.exports = React.createClass({
getInitialState: function () {
    return {

    };
  },
  componentWillMount: function () {

  },

  componentDidMount: function() {
    clearInterval(this.intervalID)
  },

  _handleClick: function () {
    alert('You clicked!')
  },

    render:function(){
    return(
        <html>
        <head>
            <title> ReactJS - demo </title>
            <link rel='stylesheet' href='/style.css'/>
        </head>
        <body>
        <div>
            <h1>react js testing</h1>
            <p>This is so cool</p>
            <button onClick={this._handleClick}>Click Me!</button>
        </div>
        <script src='/bundle.js'/>
        </body>
        </html>
        );
    }

});

Server.js

require('babel-register')({
    presets:['react']
});
var express = require('express');
var app=express();
var React=require('react');
var ReactDOMServer=require('react-dom/server');
var Component=require('./Component.jsx');

app.use(express.static('public'));
app.get('/',function(request,response){
    var html=ReactDOMServer.renderToString(
        React.createElement(Component)
    )
    response.send(html)
});

var PORT=4444;
app.listen(PORT,function(){
    console.log("Node js listening in port:"+ PORT);
})

Update 1:

I am now able to pass the value to the server side rendered component as below

React.createElement(Component,{object:...})

Now the server side setup works fine.

I need to make this {object:...} available in my client.js also for client side functionality to work. Any idea how to get this value in client.js?

Upvotes: 3

Views: 2876

Answers (1)

Andrew Z
Andrew Z

Reputation: 139

React.createElement
ReactElement createElement(
    string/ReactClass type,
    [object props],
    [children ...]
)

Create and return a new ReactElement of the given type. The type argument can be either an html tag name string (eg. 'div', 'span', etc), or a ReactClass (created via React.createClass).

In the your version in the

React.createElement(Component)

u need use something like

React.createElement(Component, {obj: obj, ...: ...})

Upvotes: 1

Related Questions