diff --git a/beta/src/pages/apis/createRoot.md b/beta/src/pages/apis/createRoot.md new file mode 100644 index 00000000..33c1b4d0 --- /dev/null +++ b/beta/src/pages/apis/createRoot.md @@ -0,0 +1,430 @@ +--- +title: createRoot +--- + + + +`createRoot` lets you create a root to display React components inside a browser DOM node. + +```js +const root = createRoot(domNode, options?) +``` + + + +- [Usage](#usage) + - [Rendering an app fully built with React](#rendering-an-app-fully-built-with-react) + - [Rendering a page partially built with React](#rendering-a-page-partially-built-with-react) + - [Updating a root component](#updating-a-root-component) +- [Reference](#reference) + - [`createRoot(domNode, options?)`](#create-root) + - [`root.render(reactNode)`](#root-render) + - [`root.unmount()`](#root-unmount) +- [Troubleshooting](#troubleshooting) + - [I've created a root, but nothing is displayed](#ive-created-a-root-but-nothing-is-displayed) + - [I'm getting an error: "Target container is not a DOM element"](#im-getting-an-error-target-container-is-not-a-dom-element) + - [I'm getting an error: "Functions are not valid as a React child."](#im-getting-an-error-functions-are-not-valid-as-a-react-child) + - [My server-rendered HTML gets re-created from scratch](#my-server-rendered-html-gets-re-created-from-scratch) + +--- + +## Usage {/*usage*/} + +### Rendering an app fully built with React {/*rendering-an-app-fully-built-with-react*/} + +If your app is fully built with React, create a single root for your entire app. + +```js [[1, 3, "document.getElementById('root')"], [2, 4, ""]] +import { createRoot } from 'react-dom/client'; + +const root = createRoot(document.getElementById('root')); +root.render(); +```` + +Usually, you only need to run this code once at startup. It will: + +1. Find the browser DOM node defined in your HTML. +2. Display the React component for your app inside. + + + +```html index.html + + + My app + + +
+ + +``` + +```js index.js active +import { createRoot } from 'react-dom/client'; +import App from './App.js'; +import './styles.css'; + +const root = createRoot(document.getElementById('root')); +root.render(); +``` + +```js App.js +import { useState } from 'react'; + +export default function App() { + return ( + <> +

Hello, world!

+ + + ); +} + +function Counter() { + const [count, setCount] = useState(0); + return ( + + ); +} +``` + +
+ +**If your app is fully built with React, you shouldn't need to create any more roots, or to call [`root.render`](#root-render) again.** + +From this point on, React will manage the DOM of your entire app. To add more components, [nest them inside the `App` component.](/learn/importing-and-exporting-components) When you need to update the UI, each of your components can do this by [using state](/apis/usestate). When you need to display extra content like a modal or a tooltip outside the DOM node, [render it with a portal.](/apis/createportal) + + + +When your HTML is empty, the user sees a blank page until the app's JavaScript code loads and runs: + +```html +
+``` + +This can feel very slow! To solve this, you can generate the initial HTML from your components [on the server or during the build.](/apis/reactdomserver) Then your visitors can read text, see images, and click links before any of the JavaScript code loads. We recommend to [use a framework](/learn/start-a-new-react-project#building-with-a-full-featured-framework) that does this optimization out of the box. Depending on when it runs, this is called *server-side rendering (SSR)* or *static site generation (SSG).* + +
+ + + +**Apps using server rendering or static generation must call [`hydrateRoot`](/apis/hydrateRoot) instead of `createRoot`.** React will then *hydrate* (reuse) the DOM nodes from your HTML instead of destroying and re-creating them. + + + +--- + +### Rendering a page partially built with React {/*rendering-a-page-partially-built-with-react*/} + +If your page [isn't fully built with React](/learn/add-react-to-a-website), you can call `createRoot` multiple times to create a root for each top-level piece of UI managed by React. You can display different content in each root by calling [`root.render`](#root-render). + +Here, two different React components are rendered into two DOM nodes defined in the `index.html` file: + + + +```html public/index.html + +
+

This paragraph is not rendered by React (open index.html to verify).

+
+
+``` + +```js index.js active +import './styles.css'; +import { createRoot } from 'react-dom/client'; +import { Comments, Navigation } from './Components.js'; + +const navDomNode = document.getElementById('navigation'); +const navRoot = createRoot(navDomNode); +navRoot.render(); + +const commentDomNode = document.getElementById('comments'); +const commentRoot = createRoot(commentDomNode); +commentRoot.render(); +``` + +```js Components.js +export function Navigation() { + return ( +
    + Home + About +
+ ); +} + +function NavLink({ href, children }) { + return ( +
  • + {children} +
  • + ); +} + +export function Comments() { + return ( + <> +

    Comments

    + + + + ); +} + +function Comment({ text, author }) { + return ( +

    {text} — {author}

    + ); +} +``` + +```css +nav ul { padding: 0; margin: 0; } +nav ul li { display: inline-block; margin-right: 20px; } +``` + +
    + +You could also create a new DOM node with [`document.createElement()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement) and add it to the document manually. + +```js +const domNode = document.createElement('div'); +const root = createRoot(domNode); +root.render(); +document.body.appendChild(domNode); // You can add it anywhere in the document +``` + +To remove the React tree from the DOM node and clean up all the resources used by it, call [`root.unmount`](#root-unmount). + +```js +root.unmount(); +``` + +This is mostly useful if your React components are inside an app written in a different framework. + +--- + +### Updating a root component {/*updating-a-root-component*/} + +You can call `render` more than once on the same root. As long as the component tree structure matches up with what was previously rendered, React will [preserve the state](/learn/preserving-and-resetting-state). Notice how you can type in the input, which means that the updates from repeated `render` calls every second in this example are not destructive: + + + +```js index.js active +import { createRoot } from 'react-dom/client'; +import './styles.css'; +import App from './App.js'; + +const root = createRoot(document.getElementById('root')); + +let i = 0; +setInterval(() => { + root.render(); + i++; +}, 1000); +``` + +```js App.js +export default function App({counter}) { + return ( + <> +

    Hello, world! {counter}

    + + + ); +} +``` + +
    + +It is uncommon to call `render` multiple times. Usually, you'll [update state](/apis/usestate) inside one of the components instead. + +--- +## Reference {/*reference*/} + +### `createRoot(domNode, options?)` {/*create-root*/} + +Call `createRoot` to create a React root for displaying content inside a browser DOM element. + +```js +const domNode = document.getElementById('root'); +const root = createRoot(domNode); +``` + +React will create a root for the `domNode`, and take over managing the DOM inside it. After you've created a root, you need to call [`root.render`](#root-render) to display a React component inside of it: + +```js +root.render(); +``` + +An app fully built with React will usually only have one `createRoot` call for its root component. A page that uses "sprinkles" of React for parts of the page may have as many separate roots as needed. + +[See examples above.](#usage) + +#### Parameters {/*parameters*/} + + +* `domNode`: A [DOM element](https://developer.mozilla.org/en-US/docs/Web/API/Element). React will create a root for this DOM element and allow you to call functions on the root, such as `render` to display rendered React content. + +* **optional** `options`: A object contain options for this React root. + + * `onRecoverableError`: optional callback called when React automatically recovers from errors. + * `identifierPrefix`: optional prefix React uses for IDs generated by [`useId`](/apis/useid). Useful to avoid conflicts when using multiple roots on the same page. +#### Returns {/*returns*/} + +`createRoot` returns an object with two methods: [`render`](#root-render) and [`unmount`](#root-unmount). + +#### Caveats {/*caveats*/} +* If your app is server-rendered, using `createRoot()` is not supported. Use [`hydrateRoot()`](/apis/react-dom/client/hydrateRoot) instead. +* You'll likely have only one `createRoot` call in your app. If you use a framework, it might do this call for you. +* When you want to render a piece of JSX in a different part of the DOM tree that isn't a child of your component (for example, a modal or a tooltip), use [`createPortal`](/apis/react-dom/createPortal) instead of `createRoot`. + +--- + +### `root.render(reactNode)` {/*root-render*/} + +Call `root.render` to display a piece of [JSX](/learn/writing-markup-with-jsx) ("React node") into the React root's browser DOM node. + +```js +root.render(); +``` + +React will display `` in the `root`, and take over managing the DOM inside it. + +[See examples above.](#usage) + +#### Parameters {/*parameters*/} + +* `reactNode`: A *React node* that you want to display. This will usually be a piece of JSX like ``, but you can also pass a React element constructed with [`createElement()`](/apis/react/createElement), a string, a number, `null`, or `undefined`. + + +#### Returns {/*returns*/} + +`root.render` returns `undefined`. + +#### Caveats {/*caveats*/} + +* The first time you call `root.render`, React will clear all the existing HTML content inside the React root before rendering the React component into it. + +* If your root's DOM node contains HTML generated by React on the server or during the build, use [`hydrateRoot()`](/apis/react-dom/client/hydrateRoot) instead, which attaches the event handlers to the existing HTML. + +* If you call `render` on the same root more than once, React will update the DOM as necessary to reflect the latest JSX you passed. React will decide which parts of the DOM can be reused and which need to be recreated by ["matching it up"](/learn/preserving-and-resetting-state) with the previously rendered tree. Calling `render` on the same root again is similar to calling the [`set` function](/apis/usestate#setstate) on the root component: React avoids unnecessary DOM updates. + +--- + +### `root.unmount()` {/*root-unmount*/} + +Call `root.unmount` to destroy a rendered tree inside a React root. + +```js +root.unmount(); +``` + +An app fully built with React will usually not have any calls to `root.unmount`. + +This is mostly useful if your React root's DOM node (or any of its ancestors) may get removed from the DOM by some other code. For example, imagine a jQuery tab panel that removes inactive tabs from the DOM. If a tab gets removed, everything inside it (including the React roots inside) would get removed from the DOM as well. In that case, you need to tell React to "stop" managing the removed root's content by calling `root.unmount`. Otherwise, the components inside the removed root won't know to clean up and free up global resources like subscriptions. + +Calling `root.unmount` will unmount all the components in the root and "detach" React from the root DOM node, including removing any event handlers or state in the tree. + + +#### Parameters {/*parameters*/} + +`root.unmount` does not accept any parameters. + + +#### Returns {/*returns*/} + +`root.unmount` returns `undefined`. + +#### Caveats {/*caveats*/} + +* Calling `root.unmount` will unmount all the components in the tree and "detach" React from the root DOM node. + +* Once you call `root.unmount` you cannot call `root.render` again on the same root. Attempting to call `root.render` on an unmounted root will throw a "Cannot update an unmounted root" error. However, you can create a new root for the same DOM node after the previous root for that node has been unmounted. + +--- + +## Troubleshooting {/*troubleshooting*/} + +### I've created a root, but nothing is displayed {/*ive-created-a-root-but-nothing-is-displayed*/} + +Make sure you haven't forgotten to actually *render* your app into the root: + +```js {5} +import { createRoot } from 'react-dom/client'; +import App from './App.js'; + +const root = createRoot(document.getElementById('root')); +root.render(); +```` + +Until you do that, nothing is displayed. + +### I'm getting an error: "Target container is not a DOM element" {/*im-getting-an-error-target-container-is-not-a-dom-element*/} + +This error means that whatever you're passing to `createRoot` is not a DOM node. + +If you're not sure what's happening, try logging it: + +```js {2} +const domNode = document.getElementById('root'); +console.log(domNode); // ??? +const root = createRoot(domNode); +root.render(); +```` + +For example, if `domNode` is `null`, it means that [`getElementById`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById) returned `null`. This will happen if there is no node in the document with the given ID at the time of your call. There may be a few reasons for it: + +1. The ID you're looking for might differ from the ID you used in the HTML file. Check for typos! +2. Your bundle's `