diff --git a/src/content/reference/react-dom/client/createRoot.md b/src/content/reference/react-dom/client/createRoot.md index b336b6e5e..31b0064b9 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` permite que você crie uma raiz para exibir componentes do React dentro de um nó do DOM do navegador. ```js const root = createRoot(domNode, options?) @@ -16,11 +16,11 @@ const root = createRoot(domNode, options?) --- -## Reference {/*reference*/} +## Referência {/*reference*/} ### `createRoot(domNode, options?)` {/*createroot*/} -Call `createRoot` to create a React root for displaying content inside a browser DOM element. +Chame `createRoot` para criar uma raiz React para exibir conteúdo dentro de um elemento do DOM do navegador. ```js import { createRoot } from 'react-dom/client'; @@ -29,106 +29,103 @@ 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: +O React criará uma raiz para o `domNode` e assumirá o gerenciamento do DOM dentro dele. Depois de criar uma raiz, você precisará chamar [`root.render`](#root-render) para exibir um componente React dentro dela: ```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. +Um aplicativo totalmente construído com o React geralmente terá apenas uma chamada `createRoot` para seu componente raiz. Uma página que usa "espólios" de React para partes da página pode ter tantas raízes separadas quanto necessário. -[See more examples below.](#usage) +[Veja mais exemplos abaixo.](#usage) -#### Parameters {/*parameters*/} +#### Parâmetros {/*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`: Um [elemento DOM.](https://developer.mozilla.org/en-US/docs/Web/API/Element) O React criará uma raiz para este elemento DOM e permitirá que você chame funções na raiz, como `render` para exibir conteúdo React renderizado. -* **optional** `options`: An object with options for this React root. +* **opcional** `options`: Um objeto com opções para esta raiz 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. + * **opcional** `onCaughtError`: Callback chamado quando o React captura um erro em uma Boundary de Erro. Chamado com o `error` capturado pela Boundary de Erro e um objeto `errorInfo` contendo o `componentStack`. + * **opcional** `onUncaughtError`: Callback chamado quando um erro é lançado e não capturado por uma Boundary de Erro. Chamado com o `error` que foi lançado e um objeto `errorInfo` contendo o `componentStack`. + * **opcional** `onRecoverableError`: Callback chamado quando o React se recupera automaticamente de erros. Chamado com um `error` que o React lança e um objeto `errorInfo` contendo o `componentStack`. Alguns erros recuperáveis podem incluir a causa original do erro como `error.cause`. + * **opcional** `identifierPrefix`: Um prefixo de string que o React usa para IDs gerados por [`useId`.](/reference/react/useId) Útil para evitar conflitos ao usar várias raízes na mesma página. -#### Returns {/*returns*/} +#### Retorna {/*returns*/} -`createRoot` returns an object with two methods: [`render`](#root-render) and [`unmount`.](#root-unmount) +`createRoot` retorna um objeto com dois métodos: [`render`](#root-render) e [`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`. +#### Ressalvas {/*caveats*/} +* Se seu aplicativo é renderizado no servidor, o uso de `createRoot()` não é suportado. Use [`hydrateRoot()`](/reference/react-dom/client/hydrateRoot) em vez disso. +* Você provavelmente terá apenas uma chamada `createRoot` em seu aplicativo. Se você usar um framework, ele pode fazer essa chamada por você. +* Quando você deseja renderizar um pedaço de JSX em uma parte diferente da árvore DOM que não é um filho do seu componente (por exemplo, um modal ou uma tooltip), use [`createPortal`](/reference/react-dom/createPortal) em vez de `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. +Chame `root.render` para exibir um pedaço de [JSX](/learn/writing-markup-with-jsx) ("nó React") no nó DOM do navegador da raiz React. ```js root.render(); ``` -React will display `` in the `root`, and take over managing the DOM inside it. +O React exibirá `` na `root` e assumirá o gerenciamento do DOM dentro dela. -[See more examples below.](#usage) +[Veja mais exemplos abaixo.](#usage) -#### Parameters {/*root-render-parameters*/} +#### Parâmetros {/*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`: Um *nó React* que você deseja exibir. Isso geralmente será um pedaço de JSX como ``, mas você também pode passar um elemento React construído com [`createElement()`](/reference/react/createElement), uma string, um número, `null` ou `undefined`. +#### Retorna {/*root-render-returns*/} -#### Returns {/*root-render-returns*/} +`root.render` retorna `undefined`. -`root.render` returns `undefined`. +#### Ressalvas {/*root-render-caveats*/} -#### Caveats {/*root-render-caveats*/} +* Na primeira vez que você chama `root.render`, o React irá limpar todo o conteúdo HTML existente dentro da raiz React antes de renderizar o componente React dentro dela. -* 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. +* Se o nó DOM da sua raiz contiver HTML gerado pelo React no servidor ou durante a construção, use [`hydrateRoot()`](/reference/react-dom/client/hydrateRoot) em vez disso, que anexa os manipuladores de eventos ao HTML existente. -* 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. - -* 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. +* Se você chamar `render` na mesma raiz mais de uma vez, o React atualizará o DOM conforme necessário para refletir o JSX mais recente que você passou. O React decidirá quais partes do DOM podem ser reutilizadas e quais precisam ser recriadas por meio de ["correspondê-lo"](/learn/preserving-and-resetting-state) com a árvore renderizada anteriormente. Chamar `render` novamente na mesma raiz é similar a chamar a função [`set`](/reference/react/useState#setstate) no componente raiz: o React evita atualizações desnecessárias no DOM. --- ### `root.unmount()` {/*root-unmount*/} -Call `root.unmount` to destroy a rendered tree inside a React root. +Chame `root.unmount` para destruir uma árvore renderizada dentro de uma raiz React. ```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. +Um aplicativo totalmente construído com o React geralmente não terá chamadas para `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. +Isso é útil principalmente se o nó DOM da sua raiz React (ou qualquer um de seus ancestrais) puder ser removido do DOM por algum outro código. Por exemplo, imagine um painel de guia jQuery que remove guias inativas do DOM. Se uma guia for removida, tudo dentro dela (incluindo as raízes React dentro) também será removido do DOM. Nesse caso, você precisa informar ao React para "parar" de gerenciar o conteúdo da raiz removida chamando `root.unmount`. Caso contrário, os componentes dentro da raiz removida não saberão como liberar e liberar recursos globais como assinaturas. +Chamar `root.unmount` desmontará todos os componentes na raiz e "desanexará" o React do nó DOM da raiz, incluindo a remoção de quaisquer manipuladores de eventos ou estado na árvore. -#### Parameters {/*root-unmount-parameters*/} +#### Parâmetros {/*root-unmount-parameters*/} -`root.unmount` does not accept any parameters. +`root.unmount` não aceita parâmetros. +#### Retorna {/*root-unmount-returns*/} -#### Returns {/*root-unmount-returns*/} +`root.unmount` retorna `undefined`. -`root.unmount` returns `undefined`. +#### Ressalvas {/*root-unmount-caveats*/} -#### Caveats {/*root-unmount-caveats*/} +* Chamar `root.unmount` desmontará todos os componentes na árvore e "desanexará" o React do nó DOM da raiz. -* 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. +* Depois de chamar `root.unmount`, você não pode chamar `root.render` novamente na mesma raiz. Tentar chamar `root.render` em uma raiz desmontada lançará um erro "Não é possível atualizar uma raiz desmontada". No entanto, você pode criar uma nova raiz para o mesmo nó DOM após a raiz anterior desse nó ter sido desmontada. --- -## Usage {/*usage*/} +## Uso {/*usage*/} -### Rendering an app fully built with React {/*rendering-an-app-fully-built-with-react*/} +### Renderizando um aplicativo totalmente construído com React {/*rendering-an-app-fully-built-with-react*/} -If your app is fully built with React, create a single root for your entire app. +Se seu aplicativo é totalmente construído com React, crie uma única raiz para todo o seu aplicativo. ```js [[1, 3, "document.getElementById('root')"], [2, 4, ""]] import { createRoot } from 'react-dom/client'; @@ -137,19 +134,19 @@ const root = createRoot(document.getElementById('root')); root.render(); ``` -Usually, you only need to run this code once at startup. It will: +Normalmente, você só precisa executar este código uma vez na inicialização. Ele irá: -1. Find the browser DOM node defined in your HTML. -2. Display the React component for your app inside. +1. Encontrar o nó DOM do navegador definido em seu HTML. +2. Exibir o componente React para seu aplicativo dentro dele. ```html index.html - My app + Meu aplicativo - +
@@ -170,7 +167,7 @@ import { useState } from 'react'; export default function App() { return ( <> -

Hello, world!

+

Olá, mundo!

); @@ -180,7 +177,7 @@ function Counter() { const [count, setCount] = useState(0); return ( ); } @@ -188,46 +185,46 @@ 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.** +**Se seu aplicativo é totalmente construído com React, você não deve precisar criar mais raízes ou chamar [`root.render`](#root-render) novamente.** -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) +A partir deste ponto, o React gerenciará o DOM de todo o seu aplicativo. Para adicionar mais componentes, [aninhá-los dentro do componente `App`.](/learn/importing-and-exporting-components) Quando você precisar atualizar a interface do usuário, cada um de seus componentes pode fazer isso [usando estado.](/reference/react/useState) Quando você precisar exibir conteúdo extra, como um modal ou uma tooltip fora do nó DOM, [renderize-o com um portal.](/reference/react-dom/createPortal) -When your HTML is empty, the user sees a blank page until the app's JavaScript code loads and runs: +Quando seu HTML está vazio, o usuário vê uma página em branco até que o código JavaScript do aplicativo carregue e execute: ```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).* +Isso pode parecer muito lento! Para resolver isso, você pode gerar o HTML inicial a partir de seus componentes [no servidor ou durante a construção.](/reference/react-dom/server) Então, seus visitantes podem ler texto, ver imagens e clicar em links antes que qualquer código JavaScript carregue. Recomendamos [usar um framework](/learn/start-a-new-react-project#production-grade-react-frameworks) que faça essa otimização automaticamente. Dependendo de quando ele é executado, isso é chamado de *renderização no lado do servidor (SSR)* ou *geração de site estático (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. +**Aplicativos que usam renderização no servidor ou geração estática devem chamar [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) em vez de `createRoot`.** O React então *hidrata* (reutiliza) os nós DOM do seu HTML em vez de destruí-los e recriá-los. --- -### Rendering a page partially built with React {/*rendering-a-page-partially-built-with-react*/} +### Renderizando uma página parcialmente construída com 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) +Se sua página [não estiver totalmente construída com React](/learn/add-react-to-an-existing-project#using-react-for-a-part-of-your-existing-page), você pode chamar `createRoot` várias vezes para criar uma raiz para cada peça de UI de nível superior gerenciada pelo React. Você pode exibir conteúdos diferentes em cada raiz chamando [`root.render`.](#root-render) -Here, two different React components are rendered into two DOM nodes defined in the `index.html` file: +Aqui, dois diferentes componentes React são renderizados em dois nós DOM definidos no arquivo `index.html`: ```html public/index.html - My app + Meu aplicativo
-

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

+

Este parágrafo não é renderizado pelo React (abra o index.html para verificar).

@@ -252,8 +249,8 @@ commentRoot.render(); export function Navigation() { return (
    - Home - About + Início + Sobre
); } @@ -269,9 +266,9 @@ function NavLink({ href, children }) { export function Comments() { return ( <> -

Comments

- - +

Comentários

+ + ); } @@ -290,28 +287,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. +Você também pode criar um novo nó DOM com [`document.createElement()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement) e adicioná-lo ao documento manualmente. ```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); // Você pode adicioná-lo em qualquer lugar no documento ``` -To remove the React tree from the DOM node and clean up all the resources used by it, call [`root.unmount`.](#root-unmount) +Para remover a árvore React do nó DOM e limpar todos os recursos usados por ela, chame [`root.unmount`.](#root-unmount) ```js root.unmount(); ``` -This is mostly useful if your React components are inside an app written in a different framework. +Isso é útil principalmente se seus componentes React estiverem dentro de um aplicativo escrito em um framework diferente. --- -### Updating a root component {/*updating-a-root-component*/} +### Atualizando um componente raiz {/*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: +Você pode chamar `render` mais de uma vez na mesma raiz. Desde que a estrutura da árvore de componentes corresponda ao que foi renderizado anteriormente, o React [preservará o estado.](/learn/preserving-and-resetting-state) Note como você pode digitar na entrada, o que significa que as atualizações a partir de chamadas repetidas de `render` a cada segundo neste exemplo não são destrutivas: @@ -333,8 +330,8 @@ setInterval(() => { export default function App({counter}) { return ( <> -

Hello, world! {counter}

- +

Olá, mundo! {counter}

+ ); } @@ -342,17 +339,17 @@ export default function App({counter}) {
-It is uncommon to call `render` multiple times. Usually, your components will [update state](/reference/react/useState) instead. +É incomum chamar `render` várias vezes. Normalmente, seus componentes irão [atualizar o estado](/reference/react/useState) em vez disso. -### Show a dialog for uncaught errors {/*show-a-dialog-for-uncaught-errors*/} +### Mostrar um diálogo para erros não capturados {/*show-a-dialog-for-uncaught-errors*/} -`onUncaughtError` is only available in the latest React Canary release. +`onUncaughtError` está disponível apenas na última versão Canary do React. -By default, React will log all uncaught errors to the console. To implement your own error reporting, you can provide the optional `onUncaughtError` root option: +Por padrão, o React registrará todos os erros não capturados no console. Para implementar seu próprio relatório de erros, você pode fornecer a opção raiz opcional `onUncaughtError`: ```js [[1, 6, "onUncaughtError"], [2, 6, "error", 1], [3, 6, "errorInfo"], [4, 10, "componentStack"]] import { createRoot } from 'react-dom/client'; @@ -362,7 +359,7 @@ const root = createRoot( { onUncaughtError: (error, errorInfo) => { console.error( - 'Uncaught error', + 'Erro não capturado', error, errorInfo.componentStack ); @@ -372,12 +369,12 @@ const root = createRoot( root.render(); ``` -The onUncaughtError option is a function called with two arguments: +A onUncaughtError opção é uma função chamada com dois argumentos: -1. The error that was thrown. -2. An errorInfo object that contains the componentStack of the error. +1. O error que foi lançado. +2. Um objeto errorInfo que contém o componentStack do erro. -You can use the `onUncaughtError` root option to display error dialogs: +Você pode usar a opção de raiz `onUncaughtError` para exibir diálogos de erro: @@ -385,12 +382,12 @@ You can use the `onUncaughtError` root option to display error dialogs: - My app + Meu aplicativo - +
@@ -484,10 +481,10 @@ function reportError({ title, error, componentStack, dismissable }) { const errorCauseStack = document.getElementById("error-cause-stack"); const errorNotDismissible = document.getElementById("error-not-dismissible"); - // Set the title + // Defina o título errorTitle.innerText = title; - // Display error message and body + // Exiba a mensagem e o corpo do erro const [heading, body] = error.message.split(/\n(.*)/s); errorMessage.innerText = heading; if (body) { @@ -496,14 +493,14 @@ function reportError({ title, error, componentStack, dismissable }) { errorBody.innerText = ''; } - // Display component stack + // Exiba a pilha do componente errorComponentStack.innerText = componentStack; - // Display the call stack - // Since we already displayed the message, strip it, and the first Error: line. + // Exiba a pilha de chamadas + // Como já exibimos a mensagem, remova-a, e a primeira linha de Erro:. errorStack.innerText = error.stack.replace(error.message, '').split(/\n(.*)/s)[1]; - // Display the cause, if available + // Exiba a causa, se disponível if (error.cause) { errorCauseMessage.innerText = error.cause.message; errorCauseStack.innerText = error.cause.stack; @@ -511,7 +508,7 @@ function reportError({ title, error, componentStack, dismissable }) { } else { errorCause.classList.add('hidden'); } - // Display the close button, if dismissible + // Exiba o botão fechar, se descartável if (dismissable) { errorNotDismissible.classList.add('hidden'); errorClose.classList.remove("hidden"); @@ -520,20 +517,20 @@ function reportError({ title, error, componentStack, dismissable }) { errorClose.classList.add("hidden"); } - // Show the dialog + // Mostre o diálogo errorDialog.classList.remove("hidden"); } export function reportCaughtError({error, cause, componentStack}) { - reportError({ title: "Caught Error", error, componentStack, dismissable: true}); + reportError({ title: "Erro Capturado", error, componentStack, dismissable: true}); } export function reportUncaughtError({error, cause, componentStack}) { - reportError({ title: "Uncaught Error", error, componentStack, dismissable: false }); + reportError({ title: "Erro Não Capturado", error, componentStack, dismissable: false }); } export function reportRecoverableError({error, cause, componentStack}) { - reportError({ title: "Recoverable Error", error, componentStack, dismissable: true }); + reportError({ title: "Erro Recuperável", error, componentStack, dismissable: true }); } ``` @@ -569,9 +566,9 @@ export default function App() { return (
- This error shows the error dialog: + Este erro mostra o diálogo de erro:
); @@ -592,15 +589,15 @@ export default function App() {
-### Displaying Error Boundary errors {/*displaying-error-boundary-errors*/} +### Exibindo erros de Boundary de Erro {/*displaying-error-boundary-errors*/} -`onCaughtError` is only available in the latest React Canary release. +`onCaughtError` está disponível apenas na última versão Canary do React. -By default, React will log all errors caught by an Error Boundary to `console.error`. To override this behavior, you can provide the optional `onCaughtError` root option to handle errors caught by an [Error Boundary](/reference/react/Component#catching-rendering-errors-with-an-error-boundary): +Por padrão, o React registrará todos os erros capturados por uma Boundary de Erro em `console.error`. Para substituir esse comportamento, você pode fornecer a opção raiz opcional `onCaughtError` para lidar com erros capturados por uma [Boundary de Erro](/reference/react/Component#catching-rendering-errors-with-an-error-boundary): ```js [[1, 6, "onCaughtError"], [2, 6, "error", 1], [3, 6, "errorInfo"], [4, 10, "componentStack"]] import { createRoot } from 'react-dom/client'; @@ -610,7 +607,7 @@ const root = createRoot( { onCaughtError: (error, errorInfo) => { console.error( - 'Caught error', + 'Erro Capturado', error, errorInfo.componentStack ); @@ -620,12 +617,12 @@ const root = createRoot( root.render(); ``` -The onCaughtError option is a function called with two arguments: +A onCaughtError opção é uma função chamada com dois argumentos: -1. The error that was caught by the boundary. -2. An errorInfo object that contains the componentStack of the error. +1. O error que foi capturado pela boundary. +2. Um objeto errorInfo que contém o componentStack do erro. -You can use the `onCaughtError` root option to display error dialogs or filter known errors from logging: +Você pode usar a opção de raiz `onCaughtError` para exibir diálogos de erro ou filtrar erros conhecidos do registro: @@ -633,12 +630,12 @@ You can use the `onCaughtError` root option to display error dialogs or filter k - My app + Meu aplicativo - +
@@ -732,10 +729,10 @@ function reportError({ title, error, componentStack, dismissable }) { const errorCauseStack = document.getElementById("error-cause-stack"); const errorNotDismissible = document.getElementById("error-not-dismissible"); - // Set the title + // Defina o título errorTitle.innerText = title; - // Display error message and body + // Exiba a mensagem e o corpo do erro const [heading, body] = error.message.split(/\n(.*)/s); errorMessage.innerText = heading; if (body) { @@ -744,14 +741,14 @@ function reportError({ title, error, componentStack, dismissable }) { errorBody.innerText = ''; } - // Display component stack + // Exiba a pilha do componente errorComponentStack.innerText = componentStack; - // Display the call stack - // Since we already displayed the message, strip it, and the first Error: line. + // Exiba a pilha de chamadas + // Como já exibimos a mensagem, remova-a, e a primeira linha de Erro:. errorStack.innerText = error.stack.replace(error.message, '').split(/\n(.*)/s)[1]; - // Display the cause, if available + // Exiba a causa, se disponível if (error.cause) { errorCauseMessage.innerText = error.cause.message; errorCauseStack.innerText = error.cause.stack; @@ -759,7 +756,7 @@ function reportError({ title, error, componentStack, dismissable }) { } else { errorCause.classList.add('hidden'); } - // Display the close button, if dismissible + // Exiba o botão fechar, se descartável if (dismissable) { errorNotDismissible.classList.add('hidden'); errorClose.classList.remove("hidden"); @@ -768,20 +765,20 @@ function reportError({ title, error, componentStack, dismissable }) { errorClose.classList.add("hidden"); } - // Show the dialog + // Mostre o diálogo errorDialog.classList.remove("hidden"); } export function reportCaughtError({error, cause, componentStack}) { - reportError({ title: "Caught Error", error, componentStack, dismissable: true}); + reportError({ title: "Erro Capturado", error, componentStack, dismissable: true}); } export function reportUncaughtError({error, cause, componentStack}) { - reportError({ title: "Uncaught Error", error, componentStack, dismissable: false }); + reportError({ title: "Erro Não Capturado", error, componentStack, dismissable: false }); } export function reportRecoverableError({error, cause, componentStack}) { - reportError({ title: "Recoverable Error", error, componentStack, dismissable: true }); + reportError({ title: "Erro Recuperável", error, componentStack, dismissable: true }); } ``` @@ -829,13 +826,13 @@ export default function App() { }} > {error != null && } - This error will not show the error dialog: + Este erro não mostrará o diálogo de erro: - This error will show the error dialog: + Este erro mostrará o diálogo de erro: @@ -843,19 +840,19 @@ export default function App() { ); } -function fallbackRender({ resetErrorBoundary }) { +function fallbackRender() { return (
-

Error Boundary

-

Something went wrong.

- +

Boundary de Erro

+

Algo deu errado.

+
); } function Throw({error}) { if (error === "known") { - throw new Error('Known error') + throw new Error('Erro conhecido') } else { foo.bar = 'baz'; } @@ -876,9 +873,9 @@ function Throw({error}) {
-### Displaying a dialog for recoverable errors {/*displaying-a-dialog-for-recoverable-errors*/} +### Exibindo um diálogo para erros recuperáveis {/*displaying-a-dialog-for-recoverable-errors*/} -React may automatically render a component a second time to attempt to recover from an error thrown in render. If successful, React will log a recoverable error to the console to notify the developer. To override this behavior, you can provide the optional `onRecoverableError` root option: +O React pode automaticamente renderizar um componente uma segunda vez para tentar se recuperar de um erro lançado na renderização. Se bem-sucedido, o React registrará um erro recuperável no console para notificar o desenvolvedor. Para substituir esse comportamento, você pode fornecer a opção raiz opcional `onRecoverableError`: ```js [[1, 6, "onRecoverableError"], [2, 6, "error", 1], [3, 10, "error.cause"], [4, 6, "errorInfo"], [5, 11, "componentStack"]] import { createRoot } from 'react-dom/client'; @@ -888,7 +885,7 @@ const root = createRoot( { onRecoverableError: (error, errorInfo) => { console.error( - 'Recoverable error', + 'Erro Recuperável', error, error.cause, errorInfo.componentStack, @@ -899,12 +896,12 @@ const root = createRoot( root.render(); ``` -The onRecoverableError option is a function called with two arguments: +A onRecoverableError opção é uma função chamada com dois argumentos: -1. The error that React throws. Some errors may include the original cause as error.cause. -2. An errorInfo object that contains the componentStack of the error. +1. O error que o React lança. Alguns erros podem incluir a causa original como error.cause. +2. Um objeto errorInfo que contém o componentStack do erro. -You can use the `onRecoverableError` root option to display error dialogs: +Você pode usar a opção de raiz `onRecoverableError` para exibir diálogos de erro: @@ -912,12 +909,12 @@ You can use the `onRecoverableError` root option to display error dialogs: - My app + Meu aplicativo - +
@@ -1011,10 +1008,10 @@ function reportError({ title, error, componentStack, dismissable }) { const errorCauseStack = document.getElementById("error-cause-stack"); const errorNotDismissible = document.getElementById("error-not-dismissible"); - // Set the title + // Defina o título errorTitle.innerText = title; - // Display error message and body + // Exiba a mensagem e o corpo do erro const [heading, body] = error.message.split(/\n(.*)/s); errorMessage.innerText = heading; if (body) { @@ -1023,14 +1020,14 @@ function reportError({ title, error, componentStack, dismissable }) { errorBody.innerText = ''; } - // Display component stack + // Exiba a pilha do componente errorComponentStack.innerText = componentStack; - // Display the call stack - // Since we already displayed the message, strip it, and the first Error: line. + // Exiba a pilha de chamadas + // Como já exibimos a mensagem, remova-a, e a primeira linha de Erro:. errorStack.innerText = error.stack.replace(error.message, '').split(/\n(.*)/s)[1]; - // Display the cause, if available + // Exiba a causa, se disponível if (error.cause) { errorCauseMessage.innerText = error.cause.message; errorCauseStack.innerText = error.cause.stack; @@ -1038,7 +1035,7 @@ function reportError({ title, error, componentStack, dismissable }) { } else { errorCause.classList.add('hidden'); } - // Display the close button, if dismissible + // Exiba o botão fechar, se descartável if (dismissable) { errorNotDismissible.classList.add('hidden'); errorClose.classList.remove("hidden"); @@ -1047,20 +1044,20 @@ function reportError({ title, error, componentStack, dismissable }) { errorClose.classList.add("hidden"); } - // Show the dialog + // Mostre o diálogo errorDialog.classList.remove("hidden"); } export function reportCaughtError({error, cause, componentStack}) { - reportError({ title: "Caught Error", error, componentStack, dismissable: true}); + reportError({ title: "Erro Capturado", error, componentStack, dismissable: true}); } export function reportUncaughtError({error, cause, componentStack}) { - reportError({ title: "Uncaught Error", error, componentStack, dismissable: false }); + reportError({ title: "Erro Não Capturado", error, componentStack, dismissable: false }); } export function reportRecoverableError({error, cause, componentStack}) { - reportError({ title: "Recoverable Error", error, componentStack, dismissable: true }); + reportError({ title: "Erro Recuperável", error, componentStack, dismissable: true }); } ``` @@ -1087,7 +1084,7 @@ root.render(); import { useState } from 'react'; import { ErrorBoundary } from "react-error-boundary"; -// 🚩 Bug: Never do this. This will force an error. +// 🚩 Bug: Nunca faça isso. Isso forçará um erro. let errorThrown = false; export default function App() { return ( @@ -1096,8 +1093,8 @@ export default function App() { fallbackRender={fallbackRender} > {!errorThrown && } -

This component threw an error, but recovered during a second render.

-

Since it recovered, no Error Boundary was shown, but onRecoverableError was used to show an error dialog.

+

Este componente lançou um erro, mas se recuperou durante uma segunda renderização.

+

Como se recuperou, nenhuma Boundary de Erro foi exibida, mas onRecoverableError foi usado para mostrar um diálogo de erro.

@@ -1107,14 +1104,14 @@ export default function App() { function fallbackRender() { return (
-

Error Boundary

-

Something went wrong.

+

Boundary de Erro

+

Algo deu errado.

); } function Throw({error}) { - // Simulate an external value changing during concurrent render. + // Simula uma mudança de valor externo durante a renderização concorrente. errorThrown = true; foo.bar = 'baz'; } @@ -1136,11 +1133,11 @@ function Throw({error}) { --- -## Troubleshooting {/*troubleshooting*/} +## Solução de Problemas {/*troubleshooting*/} -### I've created a root, but nothing is displayed {/*ive-created-a-root-but-nothing-is-displayed*/} +### Eu criei uma raiz, mas nada é exibido {/*ive-created-a-root-but-nothing-is-displayed*/} -Make sure you haven't forgotten to actually *render* your app into the root: +Certifique-se de que você não esqueceu de realmente *renderizar* seu aplicativo na raiz: ```js {5} import { createRoot } from 'react-dom/client'; @@ -1150,37 +1147,37 @@ const root = createRoot(document.getElementById('root')); root.render(); ``` -Until you do that, nothing is displayed. +Até que você faça isso, nada é exibido. --- -### 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*/} +### Estou recebendo um erro: "Você passou um segundo argumento para 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(...)`: +Um erro comum é passar as opções para `createRoot` para `root.render(...)`: -Warning: You passed a second argument to root.render(...) but it only accepts one argument. +Aviso: Você passou um segundo argumento para root.render(...) mas ele só aceita um argumento. -To fix, pass the root options to `createRoot(...)`, not `root.render(...)`: +Para corrigir, passe as opções da raiz para `createRoot(...)`, não para `root.render(...)`: ```js {2,5} -// 🚩 Wrong: root.render only takes one argument. +// 🚩 Errado: root.render só aceita um argumento. root.render(App, {onUncaughtError}); -// ✅ Correct: pass options to createRoot. +// ✅ Correto: passe opções para 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*/} +### Estou recebendo um erro: "O contêiner de destino não é um elemento DOM" {/*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. +Esse erro significa que o que você está passando para `createRoot` não é um nó DOM. -If you're not sure what's happening, try logging it: +Se você não tem certeza do que está acontecendo, tente registrá-lo: ```js {2} const domNode = document.getElementById('root'); @@ -1189,46 +1186,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: +Por exemplo, se `domNode` for `null`, isso significa que [`getElementById`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById) retornou `null`. Isso acontecerá se não houver um nó no documento com o ID dado no momento da sua chamada. Pode haver algumas razões para isso: -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 `