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
81 changes: 40 additions & 41 deletions src/content/reference/react-dom/server/renderToString.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ title: renderToString

<Pitfall>

`renderToString` does not support streaming or waiting for data. [See the alternatives.](#alternatives)
`renderToString` não suporta streaming ou esperar por dados. [Veja as alternativas.](#alternativas)

</Pitfall>

<Intro>

`renderToString` renders a React tree to an HTML string.
`renderToString` renderiza uma árvore React para uma string HTML.

```js
const html = renderToString(reactNode, options?)
Expand All @@ -22,96 +22,96 @@ const html = renderToString(reactNode, options?)

---

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

### `renderToString(reactNode, options?)` {/*rendertostring*/}

On the server, call `renderToString` to render your app to HTML.
No servidor, chame `renderToString` para renderizar seu aplicativo em HTML.

```js
import { renderToString } from 'react-dom/server';

const html = renderToString(<App />);
```

On the client, call [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) to make the server-generated HTML interactive.
No cliente, chame [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) para tornar o HTML gerado pelo servidor interativo.

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

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

* `reactNode`: A React node you want to render to HTML. For example, a JSX node like `<App />`.
* `reactNode`: Um nó React que você deseja renderizar em HTML. Por exemplo, um nó JSX como `<App />`.

* **optional** `options`: An object for server render.
* **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 passed to [`hydrateRoot`.](/reference/react-dom/client/hydrateRoot#parameters)
* **opcional** `options`: Um objeto para renderização no servidor.
* **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 passado para [`hydrateRoot`.](/reference/react-dom/client/hydrateRoot#parameters)

#### Returns {/*returns*/}
#### Retorna {/*returns*/}

An HTML string.
Uma string HTML.

#### Caveats {/*caveats*/}
#### Ressalvas {/*caveats*/}

* `renderToString` has limited Suspense support. If a component suspends, `renderToString` immediately sends its fallback as HTML.
* `renderToString` tem suporte limitado para Suspense. Se um componente suspender, `renderToString` envia imediatamente seu fallback como HTML.

* `renderToString` works in the browser, but using it in the client code is [not recommended.](#removing-rendertostring-from-the-client-code)
* `renderToString` funciona no navegador, mas seu uso no código do cliente é [não recomendado.](#removendo-rendertostring-do-código-do-cliente)

---

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

### Rendering a React tree as HTML to a string {/*rendering-a-react-tree-as-html-to-a-string*/}
### Renderizando uma árvore React como HTML para uma string {/*rendering-a-react-tree-as-html-to-a-string*/}

Call `renderToString` to render your app to an HTML string which you can send with your server response:
Chame `renderToString` para renderizar seu aplicativo em uma string HTML que você pode enviar com sua resposta do servidor:

```js {5-6}
import { renderToString } from 'react-dom/server';

// The route handler syntax depends on your backend framework
// A sintaxe do manipulador de rota depende do seu framework de backend
app.use('/', (request, response) => {
const html = renderToString(<App />);
response.send(html);
});
```

This will produce the initial non-interactive HTML output of your React components. On the client, you will need to call [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) to *hydrate* that server-generated HTML and make it interactive.
Isso produzirá a saída HTML inicial não interativa de seus componentes React. No cliente, você precisará chamar [`hydrateRoot`](/reference/react-dom/client/hydrateRoot) para *hidratar* esse HTML gerado pelo servidor e torná-lo interativo.


<Pitfall>

`renderToString` does not support streaming or waiting for data. [See the alternatives.](#alternatives)
`renderToString` não suporta streaming ou esperar por dados. [Veja as alternativas.](#alternativas)

</Pitfall>

---

## Alternatives {/*alternatives*/}
## Alternativas {/*alternatives*/}

### Migrating from `renderToString` to a streaming method on the server {/*migrating-from-rendertostring-to-a-streaming-method-on-the-server*/}
### Migrando de `renderToString` para um método de streaming no servidor {/*migrando-de-rendertostring-para-um-método-de-streaming-no-servidor*/}

`renderToString` returns a string immediately, so it does not support streaming or waiting for data.
`renderToString` retorna uma string imediatamente, portanto, não suporta streaming ou espera por dados.

When possible, we recommend using these fully-featured alternatives:
Quando possível, recomendamos usar estas alternativas totalmente funcionais:

* If you use Node.js, use [`renderToPipeableStream`.](/reference/react-dom/server/renderToPipeableStream)
* If you use Deno or a modern edge runtime with [Web Streams](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API), use [`renderToReadableStream`.](/reference/react-dom/server/renderToReadableStream)
* Se você usa Node.js, utilize [`renderToPipeableStream`.](/reference/react-dom/server/renderToPipeableStream)
* Se você usa Deno ou um runtime moderno com [Web Streams](https://developer.mozilla.org/en-US/docs/Web/API/Streams_API), utilize [`renderToReadableStream`.](/reference/react-dom/server/renderToReadableStream)

You can continue using `renderToString` if your server environment does not support streams.
Você pode continuar usando `renderToString` se seu ambiente de servidor não suportar streams.

---

### Removing `renderToString` from the client code {/*removing-rendertostring-from-the-client-code*/}
### Removendo `renderToString` do código do cliente {/*removendo-rendertostring-do-código-do-cliente*/}

Sometimes, `renderToString` is used on the client to convert some component to HTML.
Às vezes, `renderToString` é usado no cliente para converter algum componente em HTML.

```js {1-2}
// 🚩 Unnecessary: using renderToString on the client
// 🚩 Desnecessário: usando renderToString no cliente
import { renderToString } from 'react-dom/server';

const html = renderToString(<MyIcon />);
console.log(html); // For example, "<svg>...</svg>"
console.log(html); // Por exemplo, "<svg>...</svg>"
```

Importing `react-dom/server` **on the client** unnecessarily increases your bundle size and should be avoided. If you need to render some component to HTML in the browser, use [`createRoot`](/reference/react-dom/client/createRoot) and read HTML from the DOM:
Importar `react-dom/server` **no cliente** aumenta desnecessariamente o tamanho do seu bundle e deve ser evitado. Se você precisa renderizar algum componente em HTML no navegador, utilize [`createRoot`](/reference/react-dom/client/createRoot) e leia o HTML do DOM:

```js
import { createRoot } from 'react-dom/client';
Expand All @@ -122,20 +122,19 @@ const root = createRoot(div);
flushSync(() => {
root.render(<MyIcon />);
});
console.log(div.innerHTML); // For example, "<svg>...</svg>"
console.log(div.innerHTML); // Por exemplo, "<svg>...</svg>"
```

The [`flushSync`](/reference/react-dom/flushSync) call is necessary so that the DOM is updated before reading its [`innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML) property.
A chamada [`flushSync`](/reference/react-dom/flushSync) é necessária para que o DOM seja atualizado antes de ler sua propriedade [`innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML).

---

## Troubleshooting {/*troubleshooting*/}
## Solução de Problemas {/*troubleshooting*/}

### When a component suspends, the HTML always contains a fallback {/*when-a-component-suspends-the-html-always-contains-a-fallback*/}
### Quando um componente suspende, o HTML sempre contém um fallback {/*when-a-component-suspends-the-html-always-contains-a-fallback*/}

`renderToString` does not fully support Suspense.
`renderToString` não suporta totalmente o Suspense.

If some component suspends (for example, because it's defined with [`lazy`](/reference/react/lazy) or fetches data), `renderToString` will not wait for its content to resolve. Instead, `renderToString` will find the closest [`<Suspense>`](/reference/react/Suspense) boundary above it and render its `fallback` prop in the HTML. The content will not appear until the client code loads.

To solve this, use one of the [recommended streaming solutions.](#migrating-from-rendertostring-to-a-streaming-method-on-the-server) They can stream content in chunks as it resolves on the server so that the user sees the page being progressively filled in before the client code loads.
Se algum componente suspender (por exemplo, porque está definido com [`lazy`](/reference/react/lazy) ou busca dados), `renderToString` não esperará que seu conteúdo seja resolvido. Em vez disso, `renderToString` encontrará a borda mais próxima [`<Suspense>`](/reference/react/Suspense) acima dele e renderizará sua propriedade `fallback` no HTML. O conteúdo não aparecerá até que o código do cliente carregue.

Para resolver isso, use uma das [soluções de streaming recomendadas.](#migrando-de-rendertostring-para-um-método-de-streaming-no-servidor) Elas podem transmitir conteúdo em partes à medida que se resolvem no servidor, para que o usuário veja a página sendo preenchida progressivamente antes que o código do cliente carregue.
Loading