liveBook · Manning

React root

As explained in React Quickly, Second Edition

ReactDOM.createRoot is a ReactDOM API that creates a root for rendering React content into a browser DOM container.

A React root connects React rendering to a browser DOM container. Select a dedicated element such as <div id="root"></div>, create the root with ReactDOM.createRoot(), and render a React element through it. section 1.4.2

Listing 1.2 Creating and rendering an h1 element
const reactElement = React.createElement(            #1
  'h1',                                              #1
  null,                                              #1
  'Hello world!!!'                                   #1
);                                                   #1
const domNode = document.getElementById('root');     #2
const root = ReactDOM.createRoot(domNode);           #3
root.render(reactElement);                           #4

Follow the complete first render: create an h1 element, find the root container, create a React root, and call render(). section 1.4.2

Render a first heading

const reactElement = React.createElement('h1', null, 'Hello world!!!'); const domNode = document.getElementById('root'); const root = ReactDOM.createRoot(domNode); root.render(reactElement); section 1.4.2

Keep the mounting setup predictable:

  • Place React content inside a dedicated root div rather than attaching it directly to document.body, which can conflict with other libraries or browser extensions. section 1.4.2
  • Use ReactDOM for browser DOM rendering and React Core for creating and composing React elements. section 1.7
  • Chain the calls when the setup is short: ReactDOM.createRoot(document.getElementById('root')).render(...). section 1.4.2

How React Quickly, Second Edition covers it

How deep it goes
Defines the container-to-root-to-render sequence and stops short of deeper rendering internals.
Examples
Uses a root div and a rendered Hello world h1, including both expanded and chained setup forms.
What you can do after
Apply it via ReactDOM.createRoot() and root.render() to display a React element in a web page.
How it connects
Connects ReactDOM with React elements, components, DOM rendering, JSX, and the UI layer.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Quickly, Second Edition. The section links point to the parts of the book it draws on.