Home » Reactjs » Is it OK to use React.render() multiple times in the DOM?

Is it OK to use React.render() multiple times in the DOM?

Posted by: admin November 30, 2017 Leave a comment

Questions:

I want to use React to add components multiple times throughout the DOM. This fiddle shows what I’m looking to do, and it doesn’t throw any errors. Here’s the code:

HTML:

<div id="container">
    <!-- This element's contents will be replaced with the first component. -->
</div>

<div id="second-container">
    <!-- This element's contents will be replaced with the second component. -->
</div>

JS:

var Hello = React.createClass({
    render: function() {
        return <div>Hello {this.props.name}</div>;
    }
});

React.render(<Hello name="World" />, document.getElementById('container'));

React.render(<Hello name="Second World" />, document.getElementById('second-container'));

I’ve seen this question and I’m afraid that by doing the above, I’ll be risking having React components interfere with each other. The answer to that question suggests using server-side rendering which isn’t an option for me as I’m using Django server-side.

On the other hand, maybe what I’m doing is OK because I only have one instance of the React library mounted (as opposed to multiple components calling their own instance of React)?

Is this way of using multiple DOM instances an OK way to use React?

Answers:

Yes, it is perfectly fine to call React.render multiple times on the same page. Just as you’ve suggested, the React library itself is only loaded once, but each call to React.render will create a new component instance independent of any others. (In fact, such a situation is not uncommon on sites that are in the process of transitioning to React, where some portions of the page are generated using React.render and others are not.)