diff --git a/src/content/reference/react-dom/client/hydrateRoot.md b/src/content/reference/react-dom/client/hydrateRoot.md index cc30ce22c..569a0a248 100644 --- a/src/content/reference/react-dom/client/hydrateRoot.md +++ b/src/content/reference/react-dom/client/hydrateRoot.md @@ -4,7 +4,7 @@ title: hydrateRoot -`hydrateRoot` lets you display React components inside a browser DOM node whose HTML content was previously generated by [`react-dom/server`.](/reference/react-dom/server) +`hydrateRoot` permite exibir componentes React dentro de um nó DOM do navegador cujo conteúdo HTML foi gerado anteriormente por [`react-dom/server`.](/reference/react-dom/server) ```js const root = hydrateRoot(domNode, reactNode, options?) @@ -16,11 +16,11 @@ const root = hydrateRoot(domNode, reactNode, options?) --- -## Reference {/*reference*/} +## Referência {/*reference*/} ### `hydrateRoot(domNode, reactNode, options?)` {/*hydrateroot*/} -Call `hydrateRoot` to “attach” React to existing HTML that was already rendered by React in a server environment. +Chame `hydrateRoot` para "anexar" o React ao HTML existente que já foi renderizado pelo React em um ambiente de servidor. ```js import { hydrateRoot } from 'react-dom/client'; @@ -29,101 +29,97 @@ const domNode = document.getElementById('root'); const root = hydrateRoot(domNode, reactNode); ``` -React will attach to the HTML that exists inside the `domNode`, and take over managing the DOM inside it. An app fully built with React will usually only have one `hydrateRoot` call with its root component. +O React se anexará ao HTML que existe dentro do `domNode` e assumirá o gerenciamento do DOM dentro dele. Um aplicativo completamente construído com React geralmente terá apenas uma chamada `hydrateRoot` com seu componente raiz. -[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) that was rendered as the root element on the server. +* `domNode`: Um [elemento DOM](https://developer.mozilla.org/en-US/docs/Web/API/Element) que foi renderizado como o elemento raíz no servidor. -* `reactNode`: The "React node" used to render the existing HTML. This will usually be a piece of JSX like `` which was rendered with a `ReactDOM Server` method such as `renderToPipeableStream()`. +* `reactNode`: O "nó React" usado para renderizar o HTML existente. Isso será geralmente um trecho de JSX como ``, que foi renderizado com um método do `ReactDOM Server`, como `renderToPipeableStream()`. -* **optional** `options`: An object with options for this React root. +* **opcional** `options`: Um objeto com opções para essa raiz do 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 the `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. Must be the same prefix as used on the server. + * **opcional** `onCaughtError`: Função chamada quando o React captura um erro em um Boundary de Erro. Chamado com o `error` capturado pelo Boundary de Erro e um objeto `errorInfo` contendo o `componentStack`. + * **opcional** `onUncaughtError`: Função chamada quando um erro é lançado e não é capturado por um Boundary de Erro. Chamado com o `error` lançado e um objeto `errorInfo` contendo o `componentStack`. + * **opcional** `onRecoverableError`: Função chamada quando o React se recupera automaticamente de erros. Chamado com o `error` lançado pelo React e um objeto `errorInfo` contendo o `componentStack`. Alguns erros recuperáveis podem incluir a causa do erro original 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 múltiplas raízes na mesma página. Deve ser o mesmo prefixo usado no servidor. +#### Retornos {/*returns*/} -#### Returns {/*returns*/} +`hydrateRoot` retorna um objeto com dois métodos: [`render`](#root-render) e [`unmount`.](#root-unmount) -`hydrateRoot` returns an object with two methods: [`render`](#root-render) and [`unmount`.](#root-unmount) +#### Ressalvas {/*caveats*/} -#### Caveats {/*caveats*/} - -* `hydrateRoot()` expects the rendered content to be identical with the server-rendered content. You should treat mismatches as bugs and fix them. -* In development mode, React warns about mismatches during hydration. There are no guarantees that attribute differences will be patched up in case of mismatches. This is important for performance reasons because in most apps, mismatches are rare, and so validating all markup would be prohibitively expensive. -* You'll likely have only one `hydrateRoot` call in your app. If you use a framework, it might do this call for you. -* If your app is client-rendered with no HTML rendered already, using `hydrateRoot()` is not supported. Use [`createRoot()`](/reference/react-dom/client/createRoot) instead. +* `hydrateRoot()` espera que o conteúdo renderizado seja idêntico ao conteúdo renderizado pelo servidor. Você deve tratar incompatibilidades como erros e corrigí-las. +* No modo de desenvolvimento, o React avisa sobre incompatibilidades durante a hidratação. Não há garantias de que as diferenças de atributos serão corrigidas em caso de incompatibilidades. Isso é importante por razões de desempenho, pois na maioria dos aplicativos, incompatibilidades são raras, e validar toda a marcação seria proibitivamente caro. +* Você provavelmente terá apenas uma chamada `hydrateRoot` em seu aplicativo. Se você usar um framework, ele pode fazer essa chamada por você. +* Se seu aplicativo for renderizado no cliente sem HTML renderizado anteriormente, usar `hydrateRoot()` não é suportado. Use [`createRoot()`](/reference/react-dom/client/createRoot) em vez disso. --- ### `root.render(reactNode)` {/*root-render*/} -Call `root.render` to update a React component inside a hydrated React root for a browser DOM element. +Chame `root.render` para atualizar um componente React dentro de uma raiz React hidratada para um elemento DOM do navegador. ```js root.render(); ``` -React will update `` in the hydrated `root`. - -[See more examples below.](#usage) +O React atualizará `` na `root` hidratada. -#### Parameters {/*root-render-parameters*/} +[Veja mais exemplos abaixo.](#usage) -* `reactNode`: A "React node" that you want to update. 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`. +#### Parâmetros {/*root-render-parameters*/} +* `reactNode`: Um "nó React" que você deseja atualizar. Isso será geralmente um trecho 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`. -#### Returns {/*root-render-returns*/} +#### Retornos {/*root-render-returns*/} -`root.render` returns `undefined`. +`root.render` retorna `undefined`. -#### Caveats {/*root-render-caveats*/} +#### Ressalvas {/*root-render-caveats*/} -* If you call `root.render` before the root has finished hydrating, React will clear the existing server-rendered HTML content and switch the entire root to client rendering. +* Se você chamar `root.render` antes que a raiz tenha terminado de hidratar, o React limpará o conteúdo HTML existente renderizado pelo servidor e mudará toda a raiz para a renderização do cliente. --- ### `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. 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 clean up and free up resources like subscriptions. +Um aplicativo completamente construido com 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 é mais útil se o nó DOM da raiz do seu React (ou qualquer um de seus ancestrais) puder ser removido do DOM por algum outro código. Por exemplo, imagine um painel de abas do jQuery que remove abas inativas do DOM. Se uma aba for removida, tudo dentro dela (incluindo as raízes React dentro) também será removido do DOM. 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 limparão e liberarão recursos 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 qualquer manipulador 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. +#### Retornos {/*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 root. Attempting to call `root.render` on an unmounted root will throw a "Cannot update an unmounted root" error. +* Uma vez que você chama `root.unmount`, não pode chamar `root.render` novamente na raiz. Tentar chamar `root.render` em uma raiz desmontada gerará um erro "Não é possível atualizar uma raiz desmontada". --- -## Usage {/*usage*/} +## Uso {/*usage*/} -### Hydrating server-rendered HTML {/*hydrating-server-rendered-html*/} +### Hidratando HTML renderizado pelo servidor {/*hydrating-server-rendered-html*/} -If your app's HTML was generated by [`react-dom/server`](/reference/react-dom/client/createRoot), you need to *hydrate* it on the client. +Se o HTML do seu aplicativo foi gerado por [`react-dom/server`](/reference/react-dom/client/createRoot), você precisa *hidratar* ele no cliente. ```js [[1, 3, "document.getElementById('root')"], [2, 3, ""]] import { hydrateRoot } from 'react-dom/client'; @@ -131,18 +127,18 @@ import { hydrateRoot } from 'react-dom/client'; hydrateRoot(document.getElementById('root'), ); ``` -This will hydrate the server HTML inside the browser DOM node with the React component for your app. Usually, you will do it once at startup. If you use a framework, it might do this behind the scenes for you. +Isso irá hidratar o HTML do servidor dentro do nó DOM do navegador com o componente React para seu aplicativo. Normalmente, você fará isso uma vez na inicialização. Se você usar um framework, ele pode fazer isso nos bastidores para você. -To hydrate your app, React will "attach" your components' logic to the initial generated HTML from the server. Hydration turns the initial HTML snapshot from the server into a fully interactive app that runs in the browser. +Para hidratar seu aplicativo, o React irá "anexar" a lógica dos seus componentes ao HTML gerado inicialmente do servidor. A hidratação transforma o instantâneo HTML inicial do servidor em um aplicativo totalmente interativo que roda no navegador. ```html public/index.html -

Hello, world!

+

Olá, mundo!

``` ```js src/index.js active @@ -162,7 +158,7 @@ import { useState } from 'react'; export default function App() { return ( <> -

Hello, world!

+

Olá, mundo!

); @@ -172,7 +168,7 @@ function Counter() { const [count, setCount] = useState(0); return ( ); } @@ -180,30 +176,30 @@ function Counter() {
-You shouldn't need to call `hydrateRoot` again or to call it in more places. From this point on, React will be managing the DOM of your application. To update the UI, your components will [use state](/reference/react/useState) instead. +Você não deve precisar chamar `hydrateRoot` novamente ou chamá-lo em mais lugares. A partir deste ponto, o React estará gerenciando o DOM do seu aplicativo. Para atualizar a UI, seus componentes irão [usar estado](/reference/react/useState) em vez disso. -The React tree you pass to `hydrateRoot` needs to produce **the same output** as it did on the server. +A árvore React que você passa para `hydrateRoot` precisa produzir **a mesma saída** que fazia no servidor. -This is important for the user experience. The user will spend some time looking at the server-generated HTML before your JavaScript code loads. Server rendering creates an illusion that the app loads faster by showing the HTML snapshot of its output. Suddenly showing different content breaks that illusion. This is why the server render output must match the initial render output on the client. +Isso é importante para a experiência do usuário. O usuário vai passar algum tempo olhando para o HTML gerado pelo servidor antes que seu código JavaScript carregue. A renderização no servidor cria uma ilusão de que o aplicativo carrega mais rápido, exibindo o instantâneo HTML de sua saída. Mostrar de repente conteúdo diferente quebra essa ilusão. É por isso que a saída renderizada pelo servidor deve corresponder à saída da renderização inicial no cliente. -The most common causes leading to hydration errors include: +As causas mais comuns que levam a erros de hidratação incluem: -* Extra whitespace (like newlines) around the React-generated HTML inside the root node. -* Using checks like `typeof window !== 'undefined'` in your rendering logic. -* Using browser-only APIs like [`window.matchMedia`](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia) in your rendering logic. -* Rendering different data on the server and the client. +* Espaços em branco extras (como novas linhas) ao redor do HTML gerado pelo React dentro do nó raiz. +* Usar verificações como `typeof window !== 'undefined'` na sua lógica de renderização. +* Usar APIs disponíveis apenas no navegador, como [`window.matchMedia`](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia), na sua lógica de renderização. +* Renderizar dados diferentes no servidor e no cliente. -React recovers from some hydration errors, but **you must fix them like other bugs.** In the best case, they'll lead to a slowdown; in the worst case, event handlers can get attached to the wrong elements. +O React se recupera de alguns erros de hidratação, mas **você deve corrigi-los como outros bugs.** No melhor dos casos, isso levará a uma desaceleração; no pior dos casos, os manipuladores de eventos podem ser anexados aos elementos errados. --- -### Hydrating an entire document {/*hydrating-an-entire-document*/} +### Hidratando um documento inteiro {/*hydrating-an-entire-document*/} -Apps fully built with React can render the entire document as JSX, including the [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/html) tag: +Aplicativos totalmente construídos com React podem renderizar todo o documento como JSX, incluindo a tag [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/html): ```js {3,13} function App() { @@ -213,7 +209,7 @@ function App() { - My app + Meu aplicativo @@ -223,7 +219,7 @@ function App() { } ``` -To hydrate the entire document, pass the [`document`](https://developer.mozilla.org/en-US/docs/Web/API/Window/document) global as the first argument to `hydrateRoot`: +Para hidratar o documento inteiro, passe o [`document`](https://developer.mozilla.org/en-US/docs/Web/API/Window/document) global como o primeiro argumento para `hydrateRoot`: ```js {4} import { hydrateRoot } from 'react-dom/client'; @@ -234,20 +230,20 @@ hydrateRoot(document, ); --- -### Suppressing unavoidable hydration mismatch errors {/*suppressing-unavoidable-hydration-mismatch-errors*/} +### Suprimindo erros de incompatibilidade de hidratação inevitáveis {/*suppressing-unavoidable-hydration-mismatch-errors*/} -If a single element’s attribute or text content is unavoidably different between the server and the client (for example, a timestamp), you may silence the hydration mismatch warning. +Se o atributo ou o conteúdo de texto de um único elemento for inevitavelmente diferente entre o servidor e o cliente (por exemplo, um timestamp), você pode silenciar o aviso de incompatibilidade de hidratação. -To silence hydration warnings on an element, add `suppressHydrationWarning={true}`: +Para silenciar os avisos de hidratação em um elemento, adicione `suppressHydrationWarning={true}`: ```html public/index.html -

Current Date: 01/01/2020

+

Data Atual: 01/01/2020

``` ```js src/index.js @@ -262,7 +258,7 @@ hydrateRoot(document.getElementById('root'), ); export default function App() { return (

- Current Date: {new Date().toLocaleDateString()} + Data Atual: {new Date().toLocaleDateString()}

); } @@ -270,22 +266,22 @@ export default function App() {
-This only works one level deep, and is intended to be an escape hatch. Don’t overuse it. Unless it’s text content, React still won’t attempt to patch it up, so it may remain inconsistent until future updates. +Isso funciona apenas em um nível e é destinado a ser uma saída de emergência. Não o use em excesso. A menos que seja conteúdo de texto, o React ainda não tentará corrigi-lo, portanto, ele pode permanecer inconsistente até futuras atualizações. --- -### Handling different client and server content {/*handling-different-client-and-server-content*/} +### Tratando conteúdo diferente do cliente e do servidor {/*handling-different-client-and-server-content*/} -If you intentionally need to render something different on the server and the client, you can do a two-pass rendering. Components that render something different on the client can read a [state variable](/reference/react/useState) like `isClient`, which you can set to `true` in an [Effect](/reference/react/useEffect): +Se você precisa intencionalmente renderizar algo diferente no servidor e no cliente, você pode fazer uma renderização de duas passagens. Componentes que renderizam algo diferente no cliente podem ler uma [variável de estado](/reference/react/useState) como `isClient`, que você pode definir como `true` em um [Effect](/reference/react/useEffect): ```html public/index.html -

Is Server

+

É Servidor

``` ```js src/index.js @@ -308,7 +304,7 @@ export default function App() { return (

- {isClient ? 'Is Client' : 'Is Server'} + {isClient ? 'É Cliente' : 'É Servidor'}

); } @@ -316,30 +312,30 @@ export default function App() {
-This way the initial render pass will render the same content as the server, avoiding mismatches, but an additional pass will happen synchronously right after hydration. +Dessa forma, a renderização inicial produzirá o mesmo conteúdo que o servidor, evitando incompatibilidades, mas uma passagem adicional acontecerá de forma síncrona imediatamente após a hidratação. -This approach makes hydration slower because your components have to render twice. Be mindful of the user experience on slow connections. The JavaScript code may load significantly later than the initial HTML render, so rendering a different UI immediately after hydration may also feel jarring to the user. +Essa abordagem torna a hidratação mais lenta porque seus componentes precisam renderizar duas vezes. Esteja ciente da experiência do usuário em conexões lentas. O código JavaScript pode carregar significativamente mais tarde que a renderização HTML inicial, portanto, renderizar uma UI diferente imediatamente após a hidratação pode também parecer abrupto para o usuário. --- -### Updating a hydrated root component {/*updating-a-hydrated-root-component*/} +### Atualizando um componente raiz hidratado {/*updating-a-hydrated-root-component*/} -After the root has finished hydrating, you can call [`root.render`](#root-render) to update the root React component. **Unlike with [`createRoot`](/reference/react-dom/client/createRoot), you don't usually need to do this because the initial content was already rendered as HTML.** +Depois que a raiz terminar de hidratar, você pode chamar [`root.render`](#root-render) para atualizar o componente React da raiz. **Ao contrário de [`createRoot`](/reference/react-dom/client/createRoot), você normalmente não precisa fazer isso porque o conteúdo inicial já foi renderizado como HTML.** -If you call `root.render` at some point after hydration, and 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: +Se você chamar `root.render` em algum momento após a hidratação, e a estrutura da árvore de componentes corresponder ao que foi previamente renderizado, o React [preservará o estado.](/learn/preserving-and-resetting-state) Note como você pode digitar no input, o que significa que as atualizações das chamadas `render` repetidas a cada segundo neste exemplo não são destrutivas: ```html public/index.html -

Hello, world! 0

+

Olá, mundo! 0

``` ```js src/index.js active @@ -363,8 +359,8 @@ setInterval(() => { export default function App({counter}) { return ( <> -

Hello, world! {counter}

- +

Olá, mundo! {counter}

+ ); } @@ -372,17 +368,17 @@ export default function App({counter}) {
-It is uncommon to call [`root.render`](#root-render) on a hydrated root. Usually, you'll [update state](/reference/react/useState) inside one of the components instead. +É incomum chamar [`root.render`](#root-render) em uma raiz hidratada. Normalmente, você irá [atualizar o estado](/reference/react/useState) dentro de um dos componentes 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 versão mais recente do React Canary. -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 irá registrar todos os erros não capturados no console. Para implementar sua própria solução de relatórios de erros, você pode fornecer a opção raiz opcional `onUncaughtError`: ```js [[1, 7, "onUncaughtError"], [2, 7, "error", 1], [3, 7, "errorInfo"], [4, 11, "componentStack"]] import { hydrateRoot } from 'react-dom/client'; @@ -393,7 +389,7 @@ const root = hydrateRoot( { onUncaughtError: (error, errorInfo) => { console.error( - 'Uncaught error', + 'Erro não capturado', error, errorInfo.componentStack ); @@ -403,12 +399,12 @@ const root = hydrateRoot( root.render(); ``` -The onUncaughtError option is a function called with two arguments: +A opção onUncaughtError é 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 raiz `onUncaughtError` para exibir diálogos de erro: @@ -416,12 +412,12 @@ You can use the `onUncaughtError` root option to display error dialogs: - My app + Meu aplicativo -
This error shows the error dialog:
+
Esse erro exibe o diálogo de erro:
``` @@ -518,10 +514,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 mensagem de erro e corpo const [heading, body] = error.message.split(/\n(.*)/s); errorMessage.innerText = heading; if (body) { @@ -530,14 +526,14 @@ function reportError({ title, error, componentStack, dismissable }) { errorBody.innerText = ''; } - // Display component stack + // Exiba a pilha de componentes 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 Error:. 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; @@ -545,7 +541,7 @@ function reportError({ title, error, componentStack, dismissable }) { } else { errorCause.classList.add('hidden'); } - // Display the close button, if dismissible + // Exiba o botão de fechar, se dispensável if (dismissable) { errorNotDismissible.classList.add('hidden'); errorClose.classList.remove("hidden"); @@ -554,34 +550,34 @@ function reportError({ title, error, componentStack, dismissable }) { errorClose.classList.add("hidden"); } - // Show the dialog + // Exiba 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 }); } ``` ```js src/index.js active -import { hydrateRoot } from "react-dom/client"; -import App from "./App.js"; -import {reportUncaughtError} from "./reportError"; -import "./styles.css"; +import { hydrateRoot } from 'react-dom/client'; +import App from './App.js'; +import {reportUncaughtError} from './reportError'; +import './styles.css'; import {renderToString} from 'react-dom/server'; const container = document.getElementById("root"); const root = hydrateRoot(container, , { onUncaughtError: (error, errorInfo) => { - if (error.message !== 'Known error') { + if (error.message !== 'Erro Conhecido') { reportUncaughtError({ error, componentStack: errorInfo.componentStack @@ -591,50 +587,15 @@ const root = hydrateRoot(container, , { }); ``` -```js src/App.js -import { useState } from 'react'; - -export default function App() { - const [throwError, setThrowError] = useState(false); - - if (throwError) { - foo.bar = 'baz'; - } - - return ( -
- This error shows the error dialog: - -
- ); -} -``` - -```json package.json hidden -{ - "dependencies": { - "react": "canary", - "react-dom": "canary", - "react-scripts": "^5.0.0" - }, - "main": "/index.js" -} -``` - -
- - -### 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 versão mais recente do React Canary. -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 for errors caught by an [Error Boundary](/reference/react/Component#catching-rendering-errors-with-an-error-boundary): +Por padrão, o React irá registrar todos os erros capturados por um Boundary de Erro em `console.error`. Para substituir esse comportamento, você pode fornecer a opção raiz opcional `onCaughtError` para erros capturados por um [Boundary de Erro](/reference/react/Component#catching-rendering-errors-with-an-error-boundary): ```js [[1, 7, "onCaughtError"], [2, 7, "error", 1], [3, 7, "errorInfo"], [4, 11, "componentStack"]] import { hydrateRoot } from 'react-dom/client'; @@ -645,7 +606,7 @@ const root = hydrateRoot( { onCaughtError: (error, errorInfo) => { console.error( - 'Caught error', + 'Erro Capturado', error, errorInfo.componentStack ); @@ -655,12 +616,12 @@ const root = hydrateRoot( root.render(); ``` -The onCaughtError option is a function called with two arguments: +A opção onCaughtError é 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 pelo 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 raiz `onCaughtError` para exibir diálogos de erro ou filtrar erros conhecidos do registro: @@ -668,12 +629,12 @@ You can use the `onCaughtError` root option to display error dialogs or filter k - My app + Meu aplicativo -
This error will not show the error dialog:This error will show the error dialog:
+
Esse erro não mostrará o diálogo de erro:Esse erro mostrará o diálogo de erro:
``` @@ -770,10 +731,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 mensagem de erro e corpo const [heading, body] = error.message.split(/\n(.*)/s); errorMessage.innerText = heading; if (body) { @@ -782,14 +743,14 @@ function reportError({ title, error, componentStack, dismissable }) { errorBody.innerText = ''; } - // Display component stack + // Exiba a pilha de componentes 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 Error:. 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; @@ -797,7 +758,7 @@ function reportError({ title, error, componentStack, dismissable }) { } else { errorCause.classList.add('hidden'); } - // Display the close button, if dismissible + // Exiba o botão de fechar, se dispensável if (dismissable) { errorNotDismissible.classList.add('hidden'); errorClose.classList.remove("hidden"); @@ -806,20 +767,20 @@ function reportError({ title, error, componentStack, dismissable }) { errorClose.classList.add("hidden"); } - // Show the dialog + // Exiba 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 }); } ``` @@ -832,7 +793,7 @@ import "./styles.css"; const container = document.getElementById("root"); const root = hydrateRoot(container, , { onCaughtError: (error, errorInfo) => { - if (error.message !== 'Known error') { + if (error.message !== 'Erro Conhecido') { reportCaughtError({ error, componentStack: errorInfo.componentStack @@ -850,11 +811,11 @@ export default function App() { const [error, setError] = useState(null); function handleUnknown() { - setError("unknown"); + setError("desconhecido"); } function handleKnown() { - setError("known"); + setError("conhecido"); } return ( @@ -866,13 +827,13 @@ export default function App() { }} > {error != null && } - This error will not show the error dialog: + Esse erro não mostrará o diálogo de erro: - This error will show the error dialog: + Esse erro mostrará o diálogo de erro: @@ -883,16 +844,16 @@ export default function App() { function fallbackRender({ resetErrorBoundary }) { return (
-

Error Boundary

-

Something went wrong.

- +

Boundary de Erro

+

Algo deu errado.

+
); } function Throw({error}) { - if (error === "known") { - throw new Error('Known error') + if (error === "conhecido") { + throw new Error('Erro Conhecido') } else { foo.bar = 'baz'; } @@ -913,9 +874,9 @@ function Throw({error}) {
-### Show a dialog for recoverable hydration mismatch errors {/*show-a-dialog-for-recoverable-hydration-mismatch-errors*/} +### Mostrar um diálogo para erros recuperáveis de incompatibilidade de hidratação {/*show-a-dialog-for-recoverable-hydration-mismatch-errors*/} -When React encounters a hydration mismatch, it will automatically attempt to recover by rendering on the client. By default, React will log hydration mismatch errors to `console.error`. To override this behavior, you can provide the optional `onRecoverableError` root option: +Quando o React encontra uma incompatibilidade de hidratação, ele tentará automaticamente se recuperar renderizando no cliente. Por padrão, o React registrará erros de incompatibilidade de hidratação em `console.error`. Para substituir esse comportamento, você pode fornecer a opção raiz opcional `onRecoverableError`: ```js [[1, 7, "onRecoverableError"], [2, 7, "error", 1], [3, 11, "error.cause", 1], [4, 7, "errorInfo"], [5, 12, "componentStack"]] import { hydrateRoot } from 'react-dom/client'; @@ -926,7 +887,7 @@ const root = hydrateRoot( { onRecoverableError: (error, errorInfo) => { console.error( - 'Caught error', + 'Erro capturado', error, error.cause, errorInfo.componentStack @@ -936,12 +897,12 @@ const root = hydrateRoot( ); ``` -The onRecoverableError option is a function called with two arguments: +A opção onRecoverableError é uma função chamada com dois argumentos: -1. The error 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 for hydration mismatches: +Você pode usar a opção raiz `onRecoverableError` para exibir diálogos de erro para incompatibilidades de hidratação: @@ -949,12 +910,12 @@ You can use the `onRecoverableError` root option to display error dialogs for hy - My app + Meu aplicativo -
Server
+
Servidor
``` @@ -1051,10 +1012,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 mensagem de erro e corpo const [heading, body] = error.message.split(/\n(.*)/s); errorMessage.innerText = heading; if (body) { @@ -1063,14 +1024,14 @@ function reportError({ title, error, componentStack, dismissable }) { errorBody.innerText = ''; } - // Display component stack + // Exiba a pilha de componentes 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 Error:. 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; @@ -1078,7 +1039,7 @@ function reportError({ title, error, componentStack, dismissable }) { } else { errorCause.classList.add('hidden'); } - // Display the close button, if dismissible + // Exiba o botão de fechar, se dispensável if (dismissable) { errorNotDismissible.classList.add('hidden'); errorClose.classList.remove("hidden"); @@ -1087,20 +1048,20 @@ function reportError({ title, error, componentStack, dismissable }) { errorClose.classList.add("hidden"); } - // Show the dialog + // Exiba 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 }); } ``` @@ -1129,32 +1090,24 @@ import { ErrorBoundary } from "react-error-boundary"; export default function App() { const [error, setError] = useState(null); - function handleUnknown() { - setError("unknown"); - } - - function handleKnown() { - setError("known"); - } - return ( - {typeof window !== 'undefined' ? 'Client' : 'Server'} + {typeof window !== 'undefined' ? 'Cliente' : 'Servidor'} ); } function fallbackRender({ resetErrorBoundary }) { return (
-

Error Boundary

-

Something went wrong.

- +

Boundary de Erro

+

Algo deu errado.

+
); } function Throw({error}) { - if (error === "known") { - throw new Error('Known error') + if (error === "conhecido") { + throw new Error('Erro Conhecido') } else { foo.bar = 'baz'; } @@ -1175,24 +1128,23 @@ function Throw({error}) {
-## Troubleshooting {/*troubleshooting*/} +## Solução de Problemas {/*troubleshooting*/} +### Estou recebendo um erro: "Você passou um segundo argumento para root.render" {/*im-getting-an-error-you-passed-a-second-argument-to-root-render*/} -### 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*/} - -A common mistake is to pass the options for `hydrateRoot` to `root.render(...)`: +Um erro comum é passar as opções para `hydrateRoot` 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 `hydrateRoot(...)`, not `root.render(...)`: +Para corrigir, passe as opções da raiz para `hydrateRoot(...)`, não para `root.render(...)`: ```js {2,5} -// 🚩 Wrong: root.render only takes one argument. +// 🚩 Errado: root.render aceita apenas um argumento. root.render(App, {onUncaughtError}); -// ✅ Correct: pass options to createRoot. +// ✅ Correto: passe as opções para createRoot. const root = hydrateRoot(container, , {onUncaughtError}); -``` +``` \ No newline at end of file