What if the specified container already has contents when rendering to it?

Question

In the context of this lesson, what if the specified container we are rendering to already has contents?

Answer

When the function ReactDOM.render() is first called, all contents of the container are replaced. As a result, if the container element already had some elements within it, they would be completely replaced by the new component.

For instance, say that the container element in the DOM already has contents like so,

<main id="app">
  <div>Hi there!</div>
</main>

And say that we are rendering a new component into this container,

ReactDOM.render(
  <MyComponentClass />, 
  document.getElementById('app')
);

When it renders the component, all the contents of the container will be replaced with just the <MyComponentClass /> component.

12 Likes