render()
render
renders a piece of JSX (“React element”) into a browser DOM container node. It instructs React to change the DOM inside of the container
so that it matches the passed JSX.
render(<App />, container);
render(<App />, container, callback);
Rendering the root component
To call render
, you need a piece of JSX and a DOM container:
const container = document.getElementById('root');
render(<App />, container);
The UI you want to render.
The DOM node you want to render your UI into. The container itself isn’t modified, only its children are.
In apps fully built with React, you will do this once at the top level of your app—to render the “root” component.
import './styles.css'; import {render} from 'react-dom'; import App from './App.js'; render(<App />, document.getElementById('root'));
Rendering multiple roots
If you use “sprinkles” of React here and there, call render
for each top-level piece of UI managed by React.
import './styles.css'; import { render } from 'react-dom'; import { Comments, Navigation } from './Components.js'; render( <Navigation />, document.getElementById('navigation') ); render( <Comments />, document.getElementById('comments') );
Updating the rendered tree
You can call render
more than once on the same DOM node. As long as the component tree structure matches up with what was previously rendered, React will preserve the state. Notice how you can type in the input:
import {render} from 'react-dom'; import App from './App.js'; let i = 0; setInterval(() => { render( <App counter={i} />, document.getElementById('root') ); i++; }, 1000);
You can destroy the rendered tree with unmountComponentAtNode()
.
When not to use it
- If your app uses server rendering and generates HTML on the server, use
hydrate
instead ofrender
. - If your app is fully built with React, you shouldn’t need to use
render
more than once. If you want to render something in a different part of the DOM tree (for example, a modal or a tooltip), usecreatePortal
instead.
Behavior in detail
The first time you call render
, any existing DOM elements inside container
are replaced. If you call render
again, React will update the DOM as necessary to reflect the latest JSX. React will decide which parts of the DOM can be reused and which need to be recreated by “matching it up” with the previously rendered tree. Calling render
repeatedly is similar to calling setState
—in both cases, React avoids unnecessary DOM updates.
You can pass a callback as the third argument. React will call it after your component is in the DOM.
If you render <MyComponent />
, and MyComponent
is a class component, render
will return the instance of that class. In all other cases, it will return null
.