Ad

ReactJS Server-side Rendering Issue

- 1 answer

Please help me to understand my issue.

I have the following on the server-side (Node.js):

var React = require('react');
var ReactDOMServer = require('react-dom/server');

var TestComponent = React.createClass({
  render : function() {
    return <div>test</div>
  }
});

// express router callback..
function(req, res, next) {
  res.send(ReactDOMServer.renderToString(TestComponent));
};

An example of response:

<div data-reactid=".2e2hyaaz0n4" data-react-сhecksum="1124798100">test</div>

And on the client-side:

ReactDOM.render(React.createElement(template), document.getElementById('container'));

I'm having the following error in browser console:

Uncaught Invariant Violation: Invalid tag: <div data-reactid=".2e2hyaaz0n4" data-react-checksum="1124798100">test</div>

Any help will be appreciated!

Ad

Answer

If template contains the string

'<div data-reactid=".2e2hyaaz0n4" data-react-сhecksum="1124798100">test</div>'

then this is not quite correct. You can never render plain HTML as if it were JSX. Instead you should include the server-rendered HTML as part of the page source when it is rendered, and then initialize the client-side React application using the same props as used on the server.

So, for example, using the EJS template engine:

// In Express

function(req, res, next) {
  var reactHtml = ReactDOMServer.renderToString(<TestComponent />);
  res.render('index.ejs', {reactOutput: reactHtml});
};
<!-- In a template somewhere -->
<div id="container"><%- reactOutput %></div>
// In a client-side JavaScript file

var TestComponent = React.createClass({
  render : function() {
    return <div>test</div>
  }
});

ReactDOM.render(<TestComponent />, document.getElementById('container'));

See How to Implement Node + React Isomorphic JavaScript & Why it Matters for more information.

Ad
source: stackoverflow.com
Ad