From 8f7cf9a8db07e09ee8ad09c1d79fba640478d256 Mon Sep 17 00:00:00 2001 From: "translate-react-bot[bot]" <251169733+translate-react-bot[bot]@users.noreply.github.com> Date: Wed, 4 Feb 2026 15:10:36 +0000 Subject: [PATCH 1/2] =?UTF-8?q?docs:=20translate=20`createRoot.md`=20to=20?= =?UTF-8?q?=D0=A0=D1=83=D1=81=D1=81=D0=BA=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../reference/react-dom/client/createRoot.md | 206 +++++++++--------- 1 file changed, 103 insertions(+), 103 deletions(-) diff --git a/src/content/reference/react-dom/client/createRoot.md b/src/content/reference/react-dom/client/createRoot.md index adc6a8d37a..3e079892c5 100644 --- a/src/content/reference/react-dom/client/createRoot.md +++ b/src/content/reference/react-dom/client/createRoot.md @@ -4,7 +4,7 @@ title: createRoot -`createRoot` lets you create a root to display React components inside a browser DOM node. +`createRoot` позволяет создать корневой узел для отображения React-компонентов внутри узла DOM браузера. ```js const root = createRoot(domNode, options?) @@ -16,11 +16,11 @@ const root = createRoot(domNode, options?) --- -## Reference {/*reference*/} +## Справочник {/*reference*/} ### `createRoot(domNode, options?)` {/*createroot*/} -Call `createRoot` to create a React root for displaying content inside a browser DOM element. +Вызовите `createRoot`, чтобы создать React-корень для отображения контента внутри DOM-элемента браузера. ```js import { createRoot } from 'react-dom/client'; @@ -29,73 +29,73 @@ 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: +React создаст корень для `domNode` и возьмёт на себя управление DOM внутри него. После создания корня вам нужно вызвать [`root.render`](#root-render), чтобы отобразить React-компонент внутри него: ```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. +Приложение, полностью построенное на React, обычно имеет только один вызов `createRoot` для своего корневого компонента. Страница, использующая React "точечно" для отдельных частей, может иметь столько отдельных корней, сколько необходимо. -[See more examples below.](#usage) +[См. больше примеров ниже.](#usage) -#### Parameters {/*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. +* `domNode`: [DOM-элемент.](https://developer.mozilla.org/en-US/docs/Web/API/Element) React создаст корень для этого DOM-элемента и позволит вам вызывать функции для этого корня, такие как `render`, для отображения отрендеренного React-контента. -* **optional** `options`: An object with options for this React root. +* **необязательный** `options`: Объект с опциями для этого React-корня. - * **optional** `onCaughtError`: Callback called when React catches an error in an Error Boundary. Called with the `error` caught by the Error Boundary, and an `errorInfo` object containing the `componentStack`. - * **optional** `onUncaughtError`: Callback called when an error is thrown and not caught by an Error Boundary. Called with the `error` that was thrown, and an `errorInfo` object containing the `componentStack`. - * **optional** `onRecoverableError`: Callback called when React automatically recovers from errors. Called with an `error` React throws, and an `errorInfo` object containing the `componentStack`. Some recoverable errors may include the original error cause as `error.cause`. - * **optional** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](/reference/react/useId) Useful to avoid conflicts when using multiple roots on the same page. + * **необязательный** `onCaughtError`: Функция обратного вызова, вызываемая, когда React перехватывает ошибку в Error Boundary. Вызывается с ошибкой `error`, пойманной Error Boundary, и объектом `errorInfo`, содержащим `componentStack`. + * **необязательный** `onUncaughtError`: Функция обратного вызова, вызываемая, когда выбрасывается ошибка, не перехваченная Error Boundary. Вызывается с ошибкой `error`, которая была выброшена, и объектом `errorInfo`, содержащим `componentStack`. Некоторые восстанавливаемые ошибки могут включать исходную причину ошибки как `error.cause`. + * **необязательный** `onRecoverableError`: Функция обратного вызова, вызываемая, когда React автоматически восстанавливается после ошибок. Вызывается с ошибкой `error`, которую выбрасывает React, и объектом `errorInfo`, содержащим `componentStack`. Некоторые восстанавливаемые ошибки могут включать исходную причину ошибки как `error.cause`. + * **необязательный** `identifierPrefix`: Строковый префикс, который React использует для идентификаторов, сгенерированных [`useId`.](/reference/react/useId) Полезно для предотвращения конфликтов при использовании нескольких корней на одной странице. -#### Returns {/*returns*/} +#### Возвращает {/*returns*/} -`createRoot` returns an object with two methods: [`render`](#root-render) and [`unmount`.](#root-unmount) +`createRoot` возвращает объект с двумя методами: [`render`](#root-render) и [`unmount`.](#root-unmount) -#### Caveats {/*caveats*/} -* If your app is server-rendered, using `createRoot()` is not supported. Use [`hydrateRoot()`](/reference/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`](/reference/react-dom/createPortal) instead of `createRoot`. +#### Предостережения {/*caveats*/} +* Если ваше приложение рендерится на сервере, использование `createRoot()` не поддерживается. Вместо этого используйте [`hydrateRoot()`](/reference/react-dom/client/hydrateRoot). +* Вероятно, в вашем приложении будет только один вызов `createRoot`. Если вы используете фреймворк, он может сделать этот вызов за вас. +* Когда вы хотите отобразить фрагмент JSX в другой части дерева DOM, которая не является дочерним элементом вашего компонента (например, модальное окно или всплывающая подсказка), используйте [`createPortal`](/reference/react-dom/createPortal) вместо `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. +Вызовите `root.render`, чтобы отобразить фрагмент [JSX](/learn/writing-markup-with-jsx) ("React-узел") в DOM-узле React-корня. ```js root.render(); ``` -React will display `` in the `root`, and take over managing the DOM inside it. +React отобразит `` в `root` и возьмёт на себя управление DOM внутри него. -[See more examples below.](#usage) +[См. больше примеров ниже.](#usage) -#### Parameters {/*root-render-parameters*/} +#### Параметры {/*root-render-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()`](/reference/react/createElement), a string, a number, `null`, or `undefined`. +* `reactNode`: *React-узел*, который вы хотите отобразить. Обычно это фрагмент JSX, такой как ``, но вы также можете передать React-элемент, созданный с помощью [`createElement()`](/reference/react/createElement), строку, число, `null` или `undefined`. -#### Returns {/*root-render-returns*/} +#### Возвращает {/*root-render-returns*/} -`root.render` returns `undefined`. +`root.render` возвращает `undefined`. -#### Caveats {/*root-render-caveats*/} +#### Предостережения {/*root-render-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. +* При первом вызове `root.render` React очистит всё существующее HTML-содержимое внутри React-корня перед рендерингом React-компонента. -* If your root's DOM node contains HTML generated by React on the server or during the build, use [`hydrateRoot()`](/reference/react-dom/client/hydrateRoot) instead, which attaches the event handlers to the existing HTML. +* Если DOM-узел вашего корня содержит HTML, сгенерированный React на сервере или во время сборки, вместо этого используйте [`hydrateRoot()`](/reference/react-dom/client/hydrateRoot), который подключает обработчики событий к существующему 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](/reference/react/useState#setstate) on the root component: React avoids unnecessary DOM updates. +* Если вы вызовете `render` для одного и того же корня более одного раза, React внесёт необходимые изменения в DOM, чтобы отразить последний переданный вами JSX. React решит, какие части DOM можно повторно использовать, а какие нужно пересоздать, ["сопоставив их"](/learn/preserving-and-resetting-state) с ранее отрендеренным деревом. Повторный вызов `render` для того же корня аналогичен вызову [`set` функции](/reference/react/useState#setstate) для корневого компонента: React избегает ненужных обновлений DOM. -* Although rendering is synchronous once it starts, `root.render(...)` is not. This means code after `root.render()` may run before any effects (`useLayoutEffect`, `useEffect`) of that specific render are fired. This is usually fine and rarely needs adjustment. In rare cases where effect timing matters, you can wrap `root.render(...)` in [`flushSync`](https://react.dev/reference/react-dom/client/flushSync) to ensure the initial render runs fully synchronously. +* Хотя рендеринг синхронен после его начала, `root.render(...)` таковым не является. Это означает, что код после `root.render()` может выполниться до того, как будут вызваны какие-либо эффекты (`useLayoutEffect`, `useEffect`) этого конкретного рендеринга. Обычно это нормально и редко требует корректировки. В редких случаях, когда важна синхронизация эффектов, вы можете обернуть `root.render(...)` в [`flushSync`](https://react.dev/reference/react-dom/client/flushSync), чтобы гарантировать полное синхронное выполнение начального рендеринга. ```js const root = createRoot(document.getElementById('root')); root.render(); - // 🚩 The HTML will not include the rendered yet: + // 🚩 HTML ещё не будет включать отрендеренный : console.log(document.body.innerHTML); ``` @@ -103,41 +103,41 @@ React will display `` in the `root`, and take over managing the DOM insid ### `root.unmount()` {/*root-unmount*/} -Call `root.unmount` to destroy a rendered tree inside a React root. +Вызовите `root.unmount`, чтобы уничтожить отрендеренное дерево внутри React-корня. ```js root.unmount(); ``` -An app fully built with React will usually not have any calls to `root.unmount`. +Приложение, полностью построенное на React, обычно не имеет вызовов `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. +Это в основном полезно, если DOM-узел вашего React-корня (или любой из его предков) может быть удалён из DOM другим кодом. Например, представьте себе панель вкладок jQuery, которая удаляет неактивные вкладки из DOM. Если вкладка удаляется, всё внутри неё (включая React-корни внутри) также будет удалено из DOM. В этом случае вам нужно сообщить React, чтобы он "перестал" управлять содержимым удалённого корня, вызвав `root.unmount`. В противном случае компоненты внутри удалённого корня не узнают о необходимости очистки и освобождения глобальных ресурсов, таких как подписки. -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. +Вызов `root.unmount` размонтирует все компоненты в корне и "отсоединит" React от корневого DOM-узла, включая удаление всех обработчиков событий или состояния в дереве. -#### Parameters {/*root-unmount-parameters*/} +#### Параметры {/*root-unmount-parameters*/} -`root.unmount` does not accept any parameters. +`root.unmount` не принимает никаких параметров. -#### Returns {/*root-unmount-returns*/} +#### Возвращает {/*root-unmount-returns*/} -`root.unmount` returns `undefined`. +`root.unmount` возвращает `undefined`. -#### Caveats {/*root-unmount-caveats*/} +#### Предостережения {/*root-unmount-caveats*/} -* Calling `root.unmount` will unmount all the components in the tree and "detach" React from the root DOM node. +* Вызов `root.unmount` размонтирует все компоненты в дереве и "отсоединит" React от корневого DOM-узла. -* 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. +* После вызова `root.unmount` вы не сможете снова вызвать `root.render` для того же корня. Попытка вызвать `root.render` для размонтированного корня приведёт к ошибке "Cannot update an unmounted root". Однако вы можете создать новый корень для того же DOM-узла после того, как предыдущий корень для этого узла был размонтирован. --- -## Usage {/*usage*/} +## Использование {/*usage*/} -### Rendering an app fully built with React {/*rendering-an-app-fully-built-with-react*/} +### Рендеринг приложения, полностью созданного с помощью React {/*rendering-an-app-fully-built-with-react*/} -If your app is fully built with React, create a single root for your entire app. +Если ваше приложение полностью создано с помощью React, создайте один корневой элемент для всего приложения. ```js [[1, 3, "document.getElementById('root')"], [2, 4, ""]] import { createRoot } from 'react-dom/client'; @@ -146,10 +146,10 @@ 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. +1. Найдёт DOM-узел браузера, определённый в вашем HTML. +2. Отобразит React-компонент вашего приложения внутри него. @@ -197,35 +197,35 @@ function Counter() { -**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.** +**Если ваше приложение полностью создано с помощью React, вам больше не нужно создавать новые корневые элементы или вызывать [`root.render`](#root-render) повторно.** -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.](/reference/react/useState) When you need to display extra content like a modal or a tooltip outside the DOM node, [render it with a portal.](/reference/react-dom/createPortal) +С этого момента React будет управлять DOM всего вашего приложения. Чтобы добавить больше компонентов, [вложите их внутрь компонента `App`](/learn/importing-and-exporting-components). Когда вам нужно будет обновить UI, каждый из ваших компонентов сможет сделать это [с помощью состояния](/reference/react/useState). Если вам нужно отобразить дополнительный контент, такой как модальное окно или всплывающая подсказка, вне DOM-узла, [отрендерите его с помощью портала](/reference/react-dom/createPortal). -When your HTML is empty, the user sees a blank page until the app's JavaScript code loads and runs: +Когда ваш HTML пуст, пользователь видит пустую страницу до тех пор, пока JavaScript-код приложения не загрузится и не выполнится: ```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.](/reference/react-dom/server) Then your visitors can read text, see images, and click links before any of the JavaScript code loads. We recommend [using a framework](/learn/start-a-new-react-project#production-grade-react-frameworks) 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).* +Это может ощущаться как очень медленная загрузка! Чтобы решить эту проблему, вы можете генерировать начальный HTML из ваших компонентов [на сервере или во время сборки](/reference/react-dom/server). Тогда ваши посетители смогут читать текст, видеть изображения и кликать по ссылкам до загрузки всего JavaScript-кода. Мы рекомендуем [использовать фреймворк](/learn/start-a-new-react-project#production-grade-react-frameworks), который автоматически оптимизирует это. В зависимости от того, когда он выполняется, это называется *серверным рендерингом (SSR)* или *генерацией статических сайтов (SSG)*.
-**Apps using server rendering or static generation must call [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) instead of `createRoot`.** React will then *hydrate* (reuse) the DOM nodes from your HTML instead of destroying and re-creating them. +**Приложения, использующие серверный рендеринг или генерацию статических сайтов, должны вызывать [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) вместо `createRoot`.** React затем *гидрирует* (переиспользует) DOM-узлы из вашего HTML вместо их удаления и повторного создания. --- -### Rendering a page partially built with React {/*rendering-a-page-partially-built-with-react*/} +### Рендеринг страницы, частично созданной с помощью React {/*rendering-a-page-partially-built-with-react*/} -If your page [isn't fully built with React](/learn/add-react-to-an-existing-project#using-react-for-a-part-of-your-existing-page), 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) +Если ваша страница [не полностью создана с помощью React](/learn/add-react-to-an-existing-project#using-react-for-a-part-of-your-existing-page), вы можете вызывать `createRoot` несколько раз, чтобы создать корневой элемент для каждой верхней части UI, управляемой React. Вы можете отображать разный контент в каждом корневом элементе, вызывая [`root.render`.](#root-render) -Here, two different React components are rendered into two DOM nodes defined in the `index.html` file: +Здесь два разных React-компонента рендерятся в два DOM-узла, определённых в файле `index.html`: @@ -299,28 +299,28 @@ 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. +Вы также можете создать новый DOM-узел с помощью [`document.createElement()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement) и добавить его в документ вручную. ```js const domNode = document.createElement('div'); const root = createRoot(domNode); root.render(); -document.body.appendChild(domNode); // You can add it anywhere in the document +document.body.appendChild(domNode); // Вы можете добавить его в любое место документа ``` -To remove the React tree from the DOM node and clean up all the resources used by it, call [`root.unmount`.](#root-unmount) +Чтобы удалить React-дерево из DOM-узла и освободить все используемые им ресурсы, вызовите [`root.unmount`.](#root-unmount) ```js root.unmount(); ``` -This is mostly useful if your React components are inside an app written in a different framework. +Это в основном полезно, если ваши React-компоненты находятся внутри приложения, написанного на другом фреймворке. --- -### Updating a root component {/*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: +Вы можете вызывать `render` несколько раз для одного и того же корневого элемента. Пока структура дерева компонентов совпадает с ранее отрендеренной, React [сохранит состояние.](/learn/preserving-and-resetting-state) Обратите внимание, что вы можете вводить текст в поле ввода, что означает, что обновления от повторных вызовов `render` каждую секунду в этом примере не являются деструктивными: @@ -351,11 +351,11 @@ export default function App({counter}) { -It is uncommon to call `render` multiple times. Usually, your components will [update state](/reference/react/useState) instead. +Вызывать `render` несколько раз — это нетипично. Обычно ваши компоненты вместо этого [обновляют состояние](/reference/react/useState). -### Error logging in production {/*error-logging-in-production*/} +### Логирование ошибок в продакшене {/*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`: +По умолчанию React будет логировать все ошибки в консоль. Чтобы реализовать собственную систему отчётности об ошибках, вы можете предоставить необязательные параметры корневого элемента для обработчиков ошибок: `onUncaughtError`, `onCaughtError` и `onRecoverableError`: ```js [[1, 6, "onCaughtError"], [2, 6, "error", 1], [3, 6, "errorInfo"], [4, 10, "componentStack", 15]] import { createRoot } from "react-dom/client"; @@ -374,19 +374,19 @@ const root = createRoot(container, { }); ``` -The onCaughtError option is a function called with two arguments: +Опция onCaughtError — это функция, вызываемая с двумя аргументами: -1. The error that was thrown. -2. An errorInfo object that contains the componentStack of the error. +1. Ошибка, которая была выброшена. +2. Объект errorInfo, содержащий componentStack ошибки. -Together with `onUncaughtError` and `onRecoverableError`, you can can implement your own error reporting system: +Вместе с `onUncaughtError` и `onRecoverableError` вы можете реализовать собственную систему отчётности об ошибках: ```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()` используется только в демонстрационных целях. console.error(type, error, "Component Stack: "); console.error("Component Stack: ", errorInfo.componentStack); } @@ -417,9 +417,9 @@ import { 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. + // Имейте в виду, что в режиме разработки следует удалить эти опции, + // чтобы использовать стандартные обработчики React или реализовать свой оверлей. + // Обработчики здесь указаны безусловно только в демонстрационных целях. onCaughtError: onCaughtErrorProd, onRecoverableError: onRecoverableErrorProd, onUncaughtError: onUncaughtErrorProd, @@ -474,11 +474,11 @@ export default function App() { -## Troubleshooting {/*troubleshooting*/} +## Устранение неполадок {/*troubleshooting*/} -### I've created a root, but nothing is displayed {/*ive-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'; @@ -488,13 +488,13 @@ 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" {/*im-getting-an-error-you-passed-a-second-argument-to-root-render*/} +### Я получаю ошибку: "You passed a second argument to root.render" {/*im-getting-an-error-you-passed-a-second-argument-to-root-render*/} -A common mistake is to pass the options for `createRoot` to `root.render(...)`: +Распространённая ошибка — передать опции для `createRoot` в `root.render(...)`: @@ -502,23 +502,23 @@ Warning: You passed a second argument to root.render(...) but it only accepts on -To fix, pass the root options to `createRoot(...)`, not `root.render(...)`: +Чтобы исправить это, передайте опции корневого элемента в `createRoot(...)`, а не в `root.render(...)`: ```js {2,5} -// 🚩 Wrong: root.render only takes one argument. +// 🚩 Неправильно: root.render принимает только один аргумент. root.render(App, {onUncaughtError}); -// ✅ Correct: pass options to createRoot. +// ✅ Правильно: передайте опции в createRoot. const root = createRoot(container, {onUncaughtError}); root.render(); ``` --- -### I'm getting an error: "Target container is not a DOM element" {/*im-getting-an-error-target-container-is-not-a-dom-element*/} +### Я получаю ошибку: "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. +Эта ошибка означает, что то, что вы передаёте в `createRoot`, не является DOM-узлом. -If you're not sure what's happening, try logging it: +Если вы не уверены, что происходит, попробуйте вывести это в лог: ```js {2} const domNode = document.getElementById('root'); @@ -527,46 +527,46 @@ 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: +Например, если `domNode` равен `null`, это означает, что [`getElementById`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById) вернул `null`. Это произойдёт, если в документе нет узла с указанным ID на момент вызова. Этому может быть несколько причин: -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 `