Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 39 additions & 40 deletions src/content/reference/react-dom/render.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ title: render

<Deprecated>

This API will be removed in a future major version of React.
Esta API será removida em uma futura versão principal do React.

In React 18, `render` was replaced by [`createRoot`.](/reference/react-dom/client/createRoot) Using `render` in React 18 will warn that your app will behave as if it’s running React 17. Learn more [here.](/blog/2022/03/08/react-18-upgrade-guide#updates-to-client-rendering-apis)
No React 18, `render` foi substituído por [`createRoot`.](/reference/react-dom/client/createRoot) Usar `render` no React 18 irá avisar que seu aplicativo se comportará como se estivesse executando o React 17. Saiba mais [aqui.](/blog/2022/03/08/react-18-upgrade-guide#updates-to-client-rendering-apis)

</Deprecated>

<Intro>

`render` renders a piece of [JSX](/learn/writing-markup-with-jsx) ("React node") into a browser DOM node.
`render` renderiza uma peça de [JSX](/learn/writing-markup-with-jsx) ("nó React") em um nó do DOM do navegador.

```js
render(reactNode, domNode, callback?)
Expand All @@ -24,11 +24,11 @@ render(reactNode, domNode, callback?)

---

## Reference {/*reference*/}
## Referência {/*reference*/}

### `render(reactNode, domNode, callback?)` {/*render*/}

Call `render` to display a React component inside a browser DOM element.
Chame `render` para exibir um componente React dentro de um elemento do DOM do navegador.

```js
import { render } from 'react-dom';
Expand All @@ -37,40 +37,39 @@ const domNode = document.getElementById('root');
render(<App />, domNode);
```

React will display `<App />` in the `domNode`, and take over managing the DOM inside it.
O React exibirá `<App />` no `domNode` e assumirá o controle do gerenciamento do DOM dentro dele.

An app fully built with React will usually only have one `render` call with its root component. A page that uses "sprinkles" of React for parts of the page may have as many `render` calls as needed.
Um aplicativo totalmente construído com o React geralmente terá apenas uma chamada `render` com seu componente raiz. Uma página que usa "pintadas" de React para partes da página pode ter quantas chamadas `render` forem necessárias.

[See more examples below.](#usage)
[Veja mais exemplos abaixo.](#usage)

#### Parameters {/*parameters*/}
#### Parâmetros {/*parameters*/}

* `reactNode`: A *React node* that you want to display. This will usually be a piece of JSX like `<App />`, 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á uma peça de JSX como `<App />`, mas você também pode passar um elemento React construído com [`createElement()`](/reference/react/createElement), uma string, um número, `null` ou `undefined`.

* `domNode`: A [DOM element.](https://developer.mozilla.org/en-US/docs/Web/API/Element) React will display the `reactNode` you pass inside this DOM element. From this moment, React will manage the DOM inside the `domNode` and update it when your React tree changes.
* `domNode`: Um [elemento DOM.](https://developer.mozilla.org/en-US/docs/Web/API/Element) O React exibirá o `reactNode` que você passar dentro deste elemento DOM. A partir desse momento, o React gerenciará o DOM dentro do `domNode` e o atualizará quando sua árvore React mudar.

* **optional** `callback`: A function. If passed, React will call it after your component is placed into the DOM.
* **opcional** `callback`: Uma função. Se passado, o React a chamará após seu componente ser colocado no DOM.

#### Retornos {/*returns*/}

#### Returns {/*returns*/}
`render` geralmente retorna `null`. No entanto, se o `reactNode` que você passar for um *componente de classe*, então retornará uma instância desse componente.

`render` usually returns `null`. However, if the `reactNode` you pass is a *class component*, then it will return an instance of that component.
#### Ressalvas {/*caveats*/}

#### Caveats {/*caveats*/}
* No React 18, `render` foi substituído por [`createRoot`.](/reference/react-dom/client/createRoot) Por favor, use `createRoot` para o React 18 e posteriores.

* In React 18, `render` was replaced by [`createRoot`.](/reference/react-dom/client/createRoot) Please use `createRoot` for React 18 and beyond.
* A primeira vez que você chamar `render`, o React limpará todo o conteúdo HTML existente dentro do `domNode` antes de renderizar o componente React nele. Se seu `domNode` contém HTML gerado pelo React no servidor ou durante a construção, use [`hydrate()`](/reference/react-dom/hydrate) em vez disso, que anexa os manipuladores de eventos ao HTML existente.

* The first time you call `render`, React will clear all the existing HTML content inside the `domNode` before rendering the React component into it. If your `domNode` contains HTML generated by React on the server or during the build, use [`hydrate()`](/reference/react-dom/hydrate) instead, which attaches the event handlers to the existing HTML.
* Se você chamar `render` no mesmo `domNode` mais de uma vez, o React atualizará o DOM conforme necessário para refletir o último JSX que você passou. O React decidirá quais partes do DOM podem ser reutilizadas e quais precisam ser recriadas por meio da ["correspondência"](/learn/preserving-and-resetting-state) com a árvore previamente renderizada. Chamar `render` novamente no mesmo `domNode` é semelhante a chamar a [`função set`](/reference/react/useState#setstate) no componente raiz: o React evita atualizações desnecessárias do DOM.

* If you call `render` on the same `domNode` 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 `domNode` again is similar to calling the [`set` function](/reference/react/useState#setstate) on the root component: React avoids unnecessary DOM updates.

* If your app is fully built with React, you'll likely have only one `render` 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 `render`.
* Se seu aplicativo for totalmente construído com o React, você provavelmente terá apenas uma chamada `render` em seu aplicativo. (Se você usar um framework, ele pode fazer essa chamada por você.) Quando você quiser renderizar uma peça de JSX em uma parte diferente da árvore DOM que não é filha do seu componente (por exemplo, um modal ou uma dica), use [`createPortal`](/reference/react-dom/createPortal) em vez de `render`.

---

## Usage {/*usage*/}
## Uso {/*usage*/}

Call `render` to display a <CodeStep step={1}>React component</CodeStep> inside a <CodeStep step={2}>browser DOM node</CodeStep>.
Chame `render` para exibir um <CodeStep step={1}>componente React</CodeStep> dentro de um <CodeStep step={2}>nó do DOM do navegador</CodeStep>.

```js [[1, 4, "<App />"], [2, 4, "document.getElementById('root')"]]
import { render } from 'react-dom';
Expand All @@ -79,9 +78,9 @@ import App from './App.js';
render(<App />, document.getElementById('root'));
```

### Rendering the root component {/*rendering-the-root-component*/}
### Renderizando o componente raiz {/*rendering-the-root-component*/}

In apps fully built with React, **you will usually only do this once at startup**--to render the "root" component.
Em aplicativos totalmente construídos com o React, **você geralmente fará isso apenas uma vez na inicialização**--para renderizar o componente "raiz".

<Sandpack>

Expand All @@ -95,26 +94,26 @@ render(<App />, document.getElementById('root'));

```js src/App.js
export default function App() {
return <h1>Hello, world!</h1>;
return <h1>Olá, mundo!</h1>;
}
```

</Sandpack>

Usually you shouldn't need to call `render` 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)
Geralmente, você não deve precisar chamar `render` novamente ou chamá-lo em mais lugares. A partir desse ponto, o React estará gerenciando o DOM de sua aplicação. Para atualizar a interface do usuário, seus componentes irão [usar estado.](/reference/react/useState)

---

### Rendering multiple roots {/*rendering-multiple-roots*/}
### Renderizando múltiplas raízes {/*rendering-multiple-roots*/}

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), call `render` for each top-level piece of UI managed by React.
Se sua página [não for totalmente construída com o React](/learn/add-react-to-an-existing-project#using-react-for-a-part-of-your-existing-page), chame `render` para cada peça de UI de nível superior gerenciada pelo React.

<Sandpack>

```html public/index.html
<nav id="navigation"></nav>
<main>
<p>This paragraph is not rendered by React (open index.html to verify).</p>
<p>Este parágrafo não é renderizado pelo React (abra index.html para verificar).</p>
<section id="comments"></section>
</main>
```
Expand All @@ -139,8 +138,8 @@ render(
export function Navigation() {
return (
<ul>
<NavLink href="/">Home</NavLink>
<NavLink href="/about">About</NavLink>
<NavLink href="/">Início</NavLink>
<NavLink href="/about">Sobre</NavLink>
</ul>
);
}
Expand All @@ -156,9 +155,9 @@ function NavLink({ href, children }) {
export function Comments() {
return (
<>
<h2>Comments</h2>
<Comment text="Hello!" author="Sophie" />
<Comment text="How are you?" author="Sunil" />
<h2>Comentários</h2>
<Comment text="Olá!" author="Sophie" />
<Comment text="Como você está?" author="Sunil" />
</>
);
}
Expand All @@ -177,13 +176,13 @@ nav ul li { display: inline-block; margin-right: 20px; }

</Sandpack>

You can destroy the rendered trees with [`unmountComponentAtNode()`.](/reference/react-dom/unmountComponentAtNode)
Você pode destruir as árvores renderizadas com [`unmountComponentAtNode()`.](/reference/react-dom/unmountComponentAtNode)

---

### Updating the rendered tree {/*updating-the-rendered-tree*/}
### Atualizando a árvore renderizada {/*updating-the-rendered-tree*/}

You can call `render` more than once on the same DOM node. 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 are not destructive:
Você pode chamar `render` mais de uma vez no mesmo nó DOM. Desde que a estrutura da árvore de componentes corresponda ao que foi renderizado anteriormente, o React irá [preservar o estado.](/learn/preserving-and-resetting-state) Observe como você pode digitar na entrada, o que significa que as atualizações das chamadas de `render` repetidas a cada segundo não são destrutivas:

<Sandpack>

Expand All @@ -206,13 +205,13 @@ setInterval(() => {
export default function App({counter}) {
return (
<>
<h1>Hello, world! {counter}</h1>
<input placeholder="Type something here" />
<h1>Olá, mundo! {counter}</h1>
<input placeholder="Digite algo aqui" />
</>
);
}
```

</Sandpack>

It is uncommon to call `render` multiple times. Usually, you'll [update state](/reference/react/useState) inside your components instead.
É incomum chamar `render` várias vezes. Geralmente, você [atualizará o estado](/reference/react/useState) dentro de seus componentes em vez disso.
Loading