Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

translate spanish hydrateRoot. #584

Merged
merged 3 commits into from
Dec 10, 2022
Merged
Changes from 2 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
130 changes: 65 additions & 65 deletions beta/src/content/apis/react-dom/client/hydrateRoot.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ title: hydrateRoot

<Intro>

`hydrateRoot` lets you display React components inside a browser DOM node whose HTML content was previously generated by [`react-dom/server`.](/apis/react-dom/server)
`hydrateRoot` te permite mostrar componentes de React dentro de un nodo DOM del navegador cuyo contenido HTML fue generado previamente por [`react-dom/server`.](/apis/react-dom/server)

```js
const root = hydrateRoot(domNode, reactNode, options?)
Expand All @@ -16,30 +16,30 @@ const root = hydrateRoot(domNode, reactNode, options?)

---

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

### Hydrating server-rendered HTML {/*hydrating-server-rendered-html*/}
### Hidratación de HTML renderizado en el servidor {/*hydrating-server-rendered-html*/}

If your app's HTML was generated by [`react-dom/server`](/apis/react-dom/client/createRoot), you need to *hydrate* it on the client.
Si el HTML de tu aplicación fue generado por [`react-dom/server`](/apis/react-dom/client/createRoot), hay que *hidratarlo* en el cliente.

```js [[1, 3, "document.getElementById('root')"], [2, 3, "<App />"]]
import {hydrateRoot} from 'react-dom/client';

hydrateRoot(document.getElementById('root'), <App />);
````

This will hydrate the server HTML inside the <CodeStep step={1}>browser DOM node</CodeStep> with the <CodeStep step={2}>React component</CodeStep> 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.
Esto hidratará el HTML del servidor dentro del <CodeStep step={1}>nodo DOM del navegador</CodeStep> con el <CodeStep step={2}>componente de React</CodeStep> para tu aplicación. Por lo general, lo harás una vez al inicio. Si utilizas un *framework*, puede que tras bambalinas lo haga por ti.

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 tu aplicación, React "adjuntará" la lógica de tus componentes al HTML inicial generado desde el servidor. La hidratación convierte la instantánea inicial de HTML del servidor en una aplicación totalmente interactiva que se ejecuta en el navegador.

<Sandpack>

```html public/index.html
<!--
HTML content inside <div id="root">...</div>
was generated from App by react-dom/server.
El contenido HTML dentro de <div id="root">...</div>
fue generado a partir de App por react-dom/server.
-->
<div id="root"><h1>Hello, world!</h1><button>You clicked me <!-- -->0<!-- --> times</button></div>
<div id="root"><h1>Hola, mundo!</h1><button>Me has hecho clic <!-- -->0<!-- --> veces</button></div>
```

```js index.js active
Expand All @@ -59,7 +59,7 @@ import { useState } from 'react';
export default function App() {
return (
<>
<h1>Hello, world!</h1>
<h1>¡Hola, mundo!</h1>
<Counter />
</>
);
Expand All @@ -69,47 +69,47 @@ function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
You clicked me {count} times
Me has hecho clic {count} veces
</button>
);
}
```

</Sandpack>

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. If you want to update the UI, your components can do this by [using state.](/apis/react/useState)
No deberías necesitar llamar a `hydrateRoot` de nuevo o llamarlo en más sitios. A partir de este punto, React gestionará el DOM de tu aplicación. Si quieres actualizar la interfaz de usuario, tus componentes pueden hacerlo [usando el estado.](/apis/react/useState)

<Pitfall>

The React tree you pass to `hydrateRoot` needs to produce **the same output** as it did on the server.
El árbol de React que pases a `hydrateRoot` tiene que producir **la misma salida** que en el 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 during hydration.
Esto es importante para la experiencia del usuario. El usuario pasará algún tiempo mirando el HTML generado por el servidor antes de que se cargue tu código JavaScript. El renderizado del servidor crea la ilusión de que la aplicación se carga más rápido al mostrar la instantánea del HTML de su salida. Mostrar de repente un contenido diferente rompe esa ilusión. Por ello, la salida de renderizado del servidor debe coincidir con la salida del renderizado inicial en el cliente durante la hidratación.

The most common causes leading to hydration errors include:
Las causas más comunes que conducen a errores de hidratación incluyen:

* 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.
* Espacios en blanco extra (como nuevas líneas) alrededor del HTML generado por React dentro del nodo raíz.
* Utilizar comprobaciones como `typeof window !== 'undefined'` en tu lógica de renderizado.
* Utilizar APIs exclusivas del navegador como [`window.matchMedia`](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia) en tu lógica de renderizado.
* Renderizar datos diferentes en el servidor y en el cliente.

React can recover from some hydration errors, but **you must fix them like other bugs.** In the best case, they'll lead to a slower app; in the worst case, event handlers would get attached to the wrong elements.
React puede recuperarse de algunos errores de hidratación, pero **debes solucionarlos como cualquier otro error.** En el mejor de los casos, conducirán a una aplicación más lenta; en el peor, los manejadores de eventos se adjuntarán a los elementos equivocados.

</Pitfall>

### Updating a hydrated root component {/*updating-a-hydrated-root-component*/}
### Actualización de un componente raíz 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`](/apis/react-dom/client/createRoot), you don't usually need to do this because the initial content was already rendered as HTML.**
Después de que la raíz haya terminado de hidratarse, puedes llamar a [`root.render`](#root-render) para actualizar el componente raíz de React. **Al contrario que con [`createRoot`](/apis/react-dom/client/createRoot), normalmente no es necesario hacerlo porque el contenido inicial ya se ha 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:
Si llamas a `root.render` en algún momento después de la hidratación, y la estructura del árbol de componentes coincide con lo que se renderizó previamente, React [preservará el estado.](/learn/preserving-and-resetting-state) Fíjate que puedes escribir en la entrada de texto, lo que significa que las actualizaciones de las llamadas sucesivas a `render` cada segundo en este ejemplo no son destructivas:

<Sandpack>

```html public/index.html
<!--
All HTML content inside <div id="root">...</div> was
generated by rendering <App /> with react-dom/server.
Todo el contenido HTML dentro de <div id="root">...</div> fue
generado al renderizar <App /> con react-dom/server.
-->
<div id="root"><h1>Hello, world! <!-- -->0</h1><input placeholder="Type something here"/></div>
<div id="root"><h1>¡Hola, mundo! <!-- -->0</h1><input placeholder="Escriba algo aquí"/></div>
```

```js index.js active
Expand All @@ -134,109 +134,109 @@ export default function App({counter}) {
return (
<>
<h1>Hello, world! {counter}</h1>
<input placeholder="Type something here" />
<input placeholder="Escriba algo aquí" />
</>
);
}
```

</Sandpack>

It is uncommon to call [`root.render`](#root-render) on a hydrated root. Usually, you'll [update state](/apis/react/useState) inside one of the components instead.
Es poco común llamar a [`root.render`](#root-render) en una raíz hidratada. Por lo general, lo que deberías hacer es [actualizar el estado](/apis/react/useState) dentro de uno de los componentes.


---
## Reference {/*reference*/}
## Referencia {/*reference*/}

### `hydrateRoot(domNode, options?)` {/*hydrate-root*/}

Call `hydrateRoot` to “attach” React to existing HTML that was already rendered by React in a server environment.
Llama a `hydrateRoot` para "adjuntar" React al HTML existente que ya fue renderizado por React en un entorno del servidor.

```js
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.
React se unirá al HTML que existe dentro de `domNode`, y se encargará de gestionar el DOM dentro de él. Una aplicación completamente construida con React normalmente sólo tendrá una llamada a `hydrateRoot` con su componente raíz.

[See examples above.](#usage)
[Consulta los ejemplos anteriores.](#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`: Un [elemento del DOM](https://developer.mozilla.org/en-US/docs/Web/API/Element) que se ha renderizado como el elemento raíz en el servidor.

* `reactNode`: The "React node" used to render the existing HTML. This will usually be a piece of JSX like `<App />` which was rendered with a `ReactDOM Server` method such as `renderToPipeableStream(<App />)`.
* `reactNode`: El "nodo de React" utilizado para renderizar el HTML existente. Normalmente será un trozo de JSX como `<App />` que se ha renderizado con un método de `ReactDOM Server` como `renderToPipeableStream(<App />)`.

* **optional** `options`: A object contain options for this React root.
* **opcional** `options`: Un objeto que contiene opciones para esta raíz de React.

* `onRecoverableError`: optional callback called when React automatically recovers from errors.
* `identifierPrefix`: optional prefix React uses for IDs generated by [`useId`.](/apis/react/useId) Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix as used on the server.
* `onRecoverableError`: *callback* opcional que se llama cuando React se recupera automáticamente de los errores.
* `identifierPrefix`: prefijo opcional que React utiliza para los IDs generados por [`useId`.](/apis/react/useId) Útil para evitar conflictos cuando se utilizan varias raíces en la misma página. Debe ser el mismo prefijo que se utiliza en el servidor.

#### Returns {/*returns*/}
#### Devuelve {/*returns*/}

`hydrateRoot` returns an object with two methods: [`render`](#root-render) and [`unmount`.](#root-unmount)
`hydrateRoot` devuelve un objeto con dos métodos: [`render`](#root-render) y [`unmount`.](#root-unmount)

#### 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()`](/apis/react-dom/client/createRoot) instead.
#### Advertencias {/*caveats*/}
* `hydrateRoot()` espera que el contenido renderizado sea idéntico al contenido renderizado por el servidor. Deberías tratar los desajustes como errores y solucionarlos.
* En el modo de desarrollo, React avisa de los desajustes durante la hidratación. No hay garantías de que las diferencias de atributos sean parcheadas en caso de desajustes. Esto es importante por razones de rendimiento, ya que en la mayoría de las aplicaciones, los desajustes son raros, por lo que validar todo el marcado sería prohibitivamente caro.
* Es probable que sólo tengas una llamada a `hydrateRoot` en tu aplicación. Si utilizas un *framework*, puede que la haga por ti.
* Si tu aplicación está renderizada en el cliente y no tiene HTML renderizado, el uso de `hydrateRoot()` no es válido. Utiliza [`createRoot()`](/apis/react-dom/client/createRoot) en su lugar.

---

### `root.render(reactNode)` {/*root-render*/}

Call `root.render` to update a React component inside a hydrated React root for a browser DOM element.
Llama a `root.render` para actualizar un componente de React dentro de una raíz de React hidratada para un elemento DOM del navegador.

```js
root.render(<App />);
```

React will update `<App />` in the hydrated `root`.
React actualizará `<App />` en la raíz hidratada (`root`).

[See examples above.](#usage)
[Consulta los ejemplos anteriores.](#usage)

#### Parameters {/*root-render-parameters*/}
#### Parámetros {/*root-render-parameters*/}

* `reactNode`: A "React node" that you want to update. This will usually be a piece of JSX like `<App />`, but you can also pass a React element constructed with [`createElement()`](/apis/react/createElement), a string, a number, `null`, or `undefined`.
* `reactNode`: Un "nodo de React" que quieres actualizar. Normalmente será un trozo de JSX como `<App />`, pero también puedes pasar un elemento React construido con [`createElement()`.](/apis/react/createElement), un *string*, un número, `null`, o `undefined`.


#### Returns {/*root-render-returns*/}
#### Devuelve {/*root-render-returns*/}

`root.render` returns `undefined`.
`root.render` devuelve `undefined`.

#### Caveats {/*root-render-caveats*/}
#### Advertencias {/*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.
* Si llamas a `root.render` antes de que la raíz haya terminado de hidratarse, React borrará el contenido HTML existente renderizado por el servidor y cambiará toda la raíz a renderizado del cliente.

---

### `root.unmount()` {/*root-unmount*/}

Call `root.unmount` to destroy a rendered tree inside a React root.
Llama a `root.unmount` para destruir un árbol renderizado dentro de una raíz de React.

```js
root.unmount();
```

An app fully built with React will usually not have any calls to `root.unmount`.
Una aplicación completamente construida con React normalmente no tendrá ninguna llamada a `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.
Esto es útil mayormente si el nodo DOM de tu raíz de React (o cualquiera de sus ancestros) puede ser eliminado del DOM por algún otro código. Por ejemplo, imagina un panel de pestañas jQuery que elimina las pestañas inactivas del DOM. Si se elimina una pestaña, todo lo que hay dentro de ella (incluyendo las raíces React que hay dentro) se eliminará también del DOM. En ese caso, tienes que decirle a React que "deje" de gestionar el contenido de la raíz eliminada llamando a `root.unmount`. De lo contrario, los componentes dentro de la raíz eliminada no sabrán limpiar y liberar recursos globales como las suscripciones.

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.
Al llamar a `root.unmount` se desmontarán todos los componentes de la raíz y se "separará" React del nodo DOM raíz, incluyendo la eliminación de cualquier controlador de eventos o estado en el árbol.


#### Parameters {/*root-unmount-parameters*/}
#### Parámetros {/*root-unmount-parameters*/}

`root.unmount` does not accept any parameters.
`root.unmount` no acepta ningún parámetro.


#### Returns {/*root-unmount-returns*/}
#### Devuelve {/*root-unmount-returns*/}

`render` returns `null`.
`render` devuelve `null`.

#### Caveats {/*root-unmount-caveats*/}
#### Advertencias {/*root-unmount-caveats*/}

* Calling `root.unmount` will unmount all the components in the tree and "detach" React from the root DOM node.
* Llamando a `root.unmount` se desmontarán todos los componentes del árbol y se "separará" React del nodo DOM raíz.

* 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.
* Una vez que se llama a `root.unmount` no se puede volver a llamar a `root.render` en la raíz. El intento de llamar a `root.render` en una raíz desmontada arrojará el error "Cannot update an unmounted root" (No se puede actualizar una raíz desmontada).