First of all, I recommend updating the version of React. The current version provides two different top-level APIs: React , which is usually used to create components, and ReactDOM , which provides DOM methods that will be used at the top level of your application.
Here you can specify:
You are trying to run code that should only be executed in a browser. NodeJS No Document . I would suggest using webpack to pack these component files and serve them in a browser.
For an isomorphic React application, you need to have a client.js file that calls the rendering function for the same component that you are trying to do inside index.js . Got it?
Understand ReactDOM.render as indicated in the documentation:
Edit the ReactElement element in the DOM in the supplied container and return a reference to the component (or returns null for idle components).
If the ReactElement was previously mapped to the container, this will perform the update and only mutate the DOM as necessary reflect the last React component.
Keep in mind that ReactDOM.render should be used only a few times and usually at the top level of your application, only once.
Having said that, your box.js should look like this:
var React = require('react'); var box = React.createClass({ render: function() { return ( <div style='padding: 10px'> this.props.text </div> ); } }); module.exports = box;
For proper operation, you will need to create the main component main-component-file.js :
var React = require('react'); var Box = require('../react-jsx/box.js'); //this is the box component var Component = React.createClass({ render: function() { return ( <html> <head> <title> React Server Rendering </title> </head> <body> <Box text='testing'/> <script src="public/bundle.js"></script> </body> </html> ); } }); module.exports = Component;
Inside bundle.js you need to make sure that it is invoked so that the main component tries to re-render:
var React = require('react'); var ReactDOM = require('react-dom'); var Component = require('main-component-file.js'); ReactDOM.render(<Component/>, document.body);
Last but not least: index.js , the server file. Change React.renderToString to ReactDOMServer.renderToString , create a React element from the main component and use it:
var element = React.createElement(Component) router.get('/react', function(req, res, next) { var markup = ReactDOMServer.renderToString(element); res.send(markup); });
Remember to include the npm react-dom/server package in your index.js .
Links used in the article: