I\'m reasonably new to React/React-Engine. I have a config on the server-side that I need to pass certain values of to client-side however I have a dependency on NODE_ENV in ord
The most common way to pass data from the server to client before rendering is to embed it in a global JavaScript variable on the page where your React is rendering.
So, for example, in the middleware where you're actually rendering some template which includes your tags with your React app, you could add the info and grab it on the template:
var config = require('../config-from-somewhere');
app.get('/', function (req, res) {
res.render('index', {config: JSON.stringify(config)});
});
And an example mustache template:
HOWEVER apparently react-engine
already provides its own way to send data do the client-side:
Data for component rendering
The actual data that gets fed into the component for rendering is the renderOptions object that express generates.
https://github.com/paypal/react-engine#data-for-component-rendering
As you can see in this example, the movies
json is simply being passed into render:
app.get('*', function(req, res) {
res.render(req.url, {
movies: require('./movies.json')
});
});
And then, by the grace of the framework's magic, probably on this line, the information is provided for your components and then the List uses it from props.movies
.
module.exports = React.createClass({
displayName: 'List',
render: function render() {
return (
Movies
Click on a movie to see the details
{this.props.movies.map(function(movie) {
return (
-
);
})}
);
}
});
So, basically add your config
to your render call and it should be available in your component's props
.
Indeed, as we can see on this line onwards, the engine merges renderOptions
and res.locals
and finally passes that down to React.
// create the data object that will be fed into the React render method.
// Data is a mash of the express' `render options` and `res.locals`
// and meta info about `react-engine`
var data = merge({
__meta: {
// get just the relative path for view file name
view: null,
markupId: Config.client.markupId
}
}, omit(options, createOptions.renderOptionsKeysToFilter));
And:
return React.createElement(Component, merge({}, data, routerProps));