createRoot·续
```js src/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 src/Components.js
export function Navigation() {
return (
<ul>
<NavLink href="/">Home</NavLink>
<NavLink href="/about">About</NavLink>
</ul>
);
}
function NavLink({ href, children }) {
return (
<li>
<a href={href}>{children}</a>
</li>
);
}
export function Comments() {
return (
<>
<h2>Comments</h2>
<Comment text="Hello!" author="Sophie" />
<Comment text="How are you?" author="Sunil" />
</>
);
}
function Comment({ text, author }) {
return (
<p>{text} — <i>{author}</i></p>
);
}
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() and add it to the document manually.
const domNode = document.createElement('div');
const root = createRoot(domNode);
root.render(<Comment />);
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();
This is mostly useful if your React components are inside an app written in a different framework.
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. 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 src/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(
```js src/App.js
export default function App({counter}) {
return (
<>
<h1>Hello, world! {counter}</h1>
<input placeholder="Type something here" />
</>
);
}
It is uncommon to call render multiple times. Usually, your components will update state instead.
Error logging in production
By default, React will log all errors to the console. To implement your own error reporting, you can provide the optional error handler root options onUncaughtError, onCaughtError and onRecoverableError:
```js [[1, 6, "onCaughtError"], [2, 6, "error", 1], [3, 6, "errorInfo"], [4, 10, "componentStack", 15]] import { createRoot } from "react-dom/client"; import { reportCaughtError } from "./reportError";
const container = document.getElementById("root"); const root = createRoot(container, { onCaughtError: (error, errorInfo) => { if (error.message !== "Known error") { reportCaughtError({ error, componentStack: errorInfo.componentStack, }); } }, });
The <CodeStep step={1}>onCaughtError</CodeStep> option is a function called with two arguments:
1. The <CodeStep step={2}>error</CodeStep> that was thrown.
2. An <CodeStep step={3}>errorInfo</CodeStep> object that contains the <CodeStep step={4}>componentStack</CodeStep> of the error.
Together with `onUncaughtError` and `onRecoverableError`, you can can implement your own error reporting system:
```js src/reportError.js
function reportError({ type, error, errorInfo }) {
// The specific implementation is up to you.
// `console.error()` is only used for demonstration purposes.
console.error(type, error, "Component Stack: ");
console.error("Component Stack: ", errorInfo.componentStack);
}
export function onCaughtErrorProd(error, errorInfo) {
if (error.message !== "Known error") {
reportError({ type: "Caught", error, errorInfo });
}
}
export function onUncaughtErrorProd(error, errorInfo) {
reportError({ type: "Uncaught", error, errorInfo });
}
export function onRecoverableErrorProd(error, errorInfo) {
reportError({ type: "Recoverable", error, errorInfo });
}
```js src/index.js active import { createRoot } from "react-dom/client"; import App from "./App.js"; import { onCaughtErrorProd, onRecoverableErrorProd, onUncaughtErrorProd, } from "./reportError";
const container = document.getElementById("root");
const root = createRoot(container, {
// Keep in mind to remove these options in development to leverage
// React's default handlers or implement your own overlay for development.
// The handlers are only specfied unconditionally here for demonstration purposes.
onCaughtError: onCaughtErrorProd,
onRecoverableError: onRecoverableErrorProd,
onUncaughtError: onUncaughtErrorProd,
});
root.render(
```js src/App.js
import { Component, useState } from "react";
function Boom() {
foo.bar = "baz";
}
class ErrorBoundary extends Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
export default function App() {
const [triggerUncaughtError, settriggerUncaughtError] = useState(false);
const [triggerCaughtError, setTriggerCaughtError] = useState(false);
return (
<>
<button onClick={() => settriggerUncaughtError(true)}>
Trigger uncaught error
</button>
{triggerUncaughtError && <Boom />}
<button onClick={() => setTriggerCaughtError(true)}>
Trigger caught error
</button>
{triggerCaughtError && (
<ErrorBoundary>
<Boom />
</ErrorBoundary>
)}
</>
);
}
Troubleshooting
I've 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: "You passed a second argument to root.render"
A common mistake is to pass the options for `createRoot` to `root.render(...)`:
Warning: You passed a second argument to root.render(...) but it only accepts one argument.
To fix, pass the root options to `createRoot(...)`, not `root.render(...)`:
```js {2,5}
// 🚩 Wrong: root.render only takes one argument.
root.render(App, {onUncaughtError});
// ✅ Correct: pass options to createRoot.
const root = createRoot(container, {onUncaughtError});
root.render(<App />);
I'm 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 `<script>` tag cannot "see" any DOM nodes that appear *after* it in the HTML.
Another common way to get this error is to write `createRoot(<App />)` instead of `createRoot(domNode)`.
---
### I'm getting an error: "Functions are not valid as a React child."
This error means that whatever you're passing to `root.render` is not a React component.
This may happen if you call `root.render` with `Component` instead of `<Component />`:
```js {2,5}
// 🚩 Wrong: App is a function, not a Component.
root.render(App);
// ✅ Correct: <App /> is a component.
root.render(<App />);
Or if you pass a function to root.render, instead of the result of calling it:
```js {2,5} // 🚩 Wrong: createApp is a function, not a component. root.render(createApp);
// ✅ Correct: call createApp to return a component. root.render(createApp());
---
### My server-rendered HTML gets re-created from scratch
If your app is server-rendered and includes the initial HTML generated by React, you might notice that creating a root and calling `root.render` deletes all that HTML, and then re-creates all the DOM nodes from scratch. This can be slower, resets focus and scroll positions, and may lose other user input.
Server-rendered apps must use [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) instead of `createRoot`:
```js {1,4-7}
import { hydrateRoot } from 'react-dom/client';
import App from './App.js';
hydrateRoot(
document.getElementById('root'),
<App />
);
Note that its API is different. In particular, usually there will be no further root.render call.
