Rendering to the DOM

createRoot mounts your React app into a real DOM node.

SyntaxcreateRoot(document.getElementById('root')).render(<App />);

React needs one place in the real page to take over. In React 18+ you use createRoot from react-dom/client to create a root, then call render with your top component.

The entry file

Vite generates src/main.jsx for you. It grabs the <div id="root"> from index.html and renders <App /> into it.

Example

Example Β· javascript
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.jsx';

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>
);

When to use it

  • A team adds React to an existing HTML page by calling createRoot on a single div without touching the rest of the server-rendered markup.
  • An analytics dashboard uses createRoot to mount a chart component into a modal container that is created dynamically after a user clicks a button.
  • A micro-frontend architecture mounts each React widget into its own DOM node using separate createRoot calls so teams can deploy independently.

More examples

Basic createRoot render

Mounts the React application into the #root DOM element β€” the minimal entry point for any React 18+ app.

Example Β· jsx
import { createRoot } from 'react-dom/client';
import App from './App';

const root = createRoot(document.getElementById('root'));
root.render(<App />);

Render wrapped in StrictMode

Wraps the app in StrictMode so React runs extra checks in development to surface potential bugs.

Example Β· jsx
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>
);

Mount multiple React roots

Shows how to embed independent React trees into multiple DOM nodes on the same server-rendered page.

Example Β· jsx
import { createRoot } from 'react-dom/client';
import SearchWidget from './SearchWidget';
import CartWidget from './CartWidget';

createRoot(document.getElementById('search')).render(<SearchWidget />);
createRoot(document.getElementById('cart')).render(<CartWidget />);

Discussion

  • Be the first to comment on this lesson.