Ben Aston
Ben Aston

Reputation: 55739

Calling ReactDOM.render more than once

Why does the following only render a single button?

const b = <button>this is a button</button>;
ReactDOM.render(b,mountNode)
ReactDOM.render(b,mountNode)
ReactDOM.render(b,mountNode)

Upvotes: 0

Views: 1760

Answers (2)

Chris
Chris

Reputation: 59511

If mountNode is a reference to a DOM element, calling ReactDOM.render(b, mountNode) means that React will insert your React Component as the innerHTML to that node.

Calling it several times effectively means that you just keep replacing the previously mounted node.

If you want 3 buttons, try creating a component that wraps them. For example:

var mountNode = document.getElementById("app");

const b = <button>this is a button</button>;
const myApp = <div>{b}{b}{b}</div>;

ReactDOM.render(myApp, mountNode);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<div id="app"></div>

Alternatively:

var mountNode = document.getElementById("app");

const B = () => <button>this is a button</button>;
const MyApp = () => <div><B /><B /><B /></div>;

ReactDOM.render(<MyApp />, mountNode);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

Upvotes: 6

RVCoder
RVCoder

Reputation: 542

In react it creates virtual DOM. Every time render method is called the previous DOM is replaced by new created DOM. It only looks for difference between previous DOM and new DOM. That's why it renders single button.

Upvotes: 2

Related Questions