Search code examples
reactjsisomorphic-javascript

How to force React to accept server markup


On the first load I render my markup completely filled with data on the server.

This works well and the client sees it as a static html till the client-side React takes over. But this client-side code throws the markup away.

I stopped React from requesting the data per AJAX on the first load (because it's already there), only if I navigate client-side with a react-router <Link> to it.

But I can't force it to simply let the markup be, till the user interacts with it.


Solution

  • You can use dangerouslySetInnerHTML attribute. For example, create a new component wrapper like this and set html property:

    export default React.createClass({
      render: function() {
    
        return <div dangerouslySetInnerHTML={ this.createMarkup() }>
    
        </div>;
      },
    
      componentDidMount: function() {
        // attach some events
      },
    
      componentWillUnmount: function() {
        // detach some events
      },
    
      shouldComponentUpdate: function() {
        return false;
      },
    
      createMarkup: function() {
        return {
          __html: this.props.html
        };
      }
    });