diff --git a/src/content/reference/react-dom/client/createRoot.md b/src/content/reference/react-dom/client/createRoot.md index adc6a8d37a..aa9f0e4852 100644 --- a/src/content/reference/react-dom/client/createRoot.md +++ b/src/content/reference/react-dom/client/createRoot.md @@ -1,10 +1,9 @@ --- 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 +15,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 +28,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`. + * **необязательный** `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 +102,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-узел вашего корневого узла (или любой из его предков) может быть удалён из 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 +145,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-компонент вашего приложения внутри него. @@ -158,7 +157,7 @@ Usually, you only need to run this code once at startup. It will: My app - +
@@ -197,35 +196,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) Когда вам нужно будет обновить пользовательский интерфейс, каждый из ваших компонентов сможет сделать это [используя состояние.](/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` несколько раз, чтобы создать корневой узел для каждой верхней части пользовательского интерфейса, управляемой 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`: @@ -236,7 +235,7 @@ Here, two different React components are rendered into two DOM nodes defined in
-

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

+

Этот параграф не рендерится React (проверьте index.html).

@@ -299,28 +298,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 +350,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 +373,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 +416,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 +473,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 +487,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 +501,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 +526,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 `