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 order to get the correct config out.
var config = {
local: { ... }
production: { ...}
}
module.exports = config[process.env.NODE_ENV]
Which works just fine server-side, however since I need to reference some of values contained in these objects on the client-side so I can't require(./config); in my React JSX.
Is there any easy way to pass this stuff into React? At the end of the day, I'd be happy if I could just pass the 'config' straight into React somehow without even having to worry about NODE_ENV on the client-side.
Thanks
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
<script>
tags with your React app, you could add the info and grab it on the template:And an example mustache template:
HOWEVER apparently
react-engine
already provides its own way to send data do the client-side: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: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
.So, basically add your
config
to your render call and it should be available in your component'sprops
.And for the very curious:
Indeed, as we can see on this line onwards, the engine merges
renderOptions
andres.locals
and finally passes that down to React.And: