You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: beta/src/content/apis/react-dom/client/hydrateRoot.md
+68-68Lines changed: 68 additions & 68 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,7 +4,7 @@ title: hydrateRoot
4
4
5
5
<Intro>
6
6
7
-
`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)
7
+
`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)
This will hydrate the server HTML inside the<CodeStep step={1}>browserDOMnode</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 dothis behind the scenes for you.
31
+
Esto hidratará el HTML del servidor dentro del<CodeStep step={1}>nodoDOMdel 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.
32
32
33
-
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.
33
+
Para hidratar tu aplicación, React "adjuntará" la lógica de tus componentes al HTMLinicial 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.
34
34
35
35
<Sandpack>
36
36
37
37
```html public/index.html
38
38
<!--
39
-
HTML content inside <div id="root">...</div>
40
-
was generated from App by react-dom/server.
39
+
El contenido HTML dentro de <div id="root">...</div>
40
+
fue generado a partir de App por react-dom/server.
41
41
-->
42
-
<div id="root"><h1>Hello, world!</h1><button>You clicked me <!-- -->0<!-- --> times</button></div>
42
+
<div id="root"><h1>Hola, mundo!</h1><button>Me has hecho clic <!-- -->0<!-- --> veces</button></div>
43
43
```
44
44
45
45
```js index.js active
@@ -59,7 +59,7 @@ import { useState } from 'react';
59
59
export default function App() {
60
60
return (
61
61
<>
62
-
<h1>Hello, world!</h1>
62
+
<h1>¡Hola, mundo!</h1>
63
63
<Counter />
64
64
</>
65
65
);
@@ -69,38 +69,38 @@ function Counter() {
69
69
const [count, setCount] = useState(0);
70
70
return (
71
71
<button onClick={() => setCount(count + 1)}>
72
-
You clicked me {count} times
72
+
Me has hecho clic {count} veces
73
73
</button>
74
74
);
75
75
}
76
76
```
77
77
78
78
</Sandpack>
79
79
80
-
You shouldn't need to call`hydrateRoot`again or to call it in more places. Fromthis point on, React will be managing the DOMof your application. If you want to update the UI, your components can dothis by [using state.](/apis/react/useState)
80
+
No deberías necesitar llamar a`hydrateRoot`de nuevo o llamarlo en más sitios. A partir de este punto, React gestionará el DOMde tu aplicación. Si quieres actualizar la interfaz de usuario, tus componentes pueden hacerlo [usando el estado.](/apis/react/useState)
81
81
82
82
<Pitfall>
83
83
84
-
The React tree you pass to `hydrateRoot`needs to produce**the same output**as it did on the server.
84
+
El árbol de React que pases a `hydrateRoot`tiene que producir**la misma salida**que en el servidor.
85
85
86
-
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.
86
+
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.
87
87
88
-
The most common causes leading to hydration errors include:
88
+
Las causas más comunes que conducen a errores de hidratación incluyen:
89
89
90
-
*Extra whitespace (like newlines) around the React-generated HTMLinside the root node.
91
-
*Using checks like`typeof window !== 'undefined'`in your rendering logic.
92
-
*Using browser-only APIs like [`window.matchMedia`](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia) in your rendering logic.
93
-
*Rendering different data on the server and the client.
90
+
*Espacios en blanco extra (como nuevas líneas) alrededor del HTMLgenerado por React dentro del nodo raíz.
91
+
*Utilizar comprobaciones como`typeof window !== 'undefined'`en tu lógica de renderizado.
92
+
*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.
93
+
*Renderizar datos diferentes en el servidor y en el cliente.
94
94
95
-
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.
95
+
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.
96
96
97
97
</Pitfall>
98
98
99
99
---
100
100
101
-
### Hydrating an entire document {/*hydrating-an-entire-document*/}
101
+
### Hidratar un documento completo {/*hydrating-an-entire-document*/}
102
102
103
-
Apps fully built with React can render the entire document from the root component, including the [`<html>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/html) tag:
103
+
Las aplicaciones construidas completamente con React pueden renderizar un documento completo a partir del componente raíz, incluyendo la etiqueta [`html`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/html):
104
104
105
105
```js {3,10}
106
106
function App() {
@@ -117,7 +117,7 @@ function App() {
117
117
}
118
118
```
119
119
120
-
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`:
120
+
Para hidratar el documento completo, pasa la variable global[`document`](https://developer.mozilla.org/en-US/docs/Web/API/Window/document) como primer argumento a `hydrateRoot`:
121
121
122
122
```js {5}
123
123
import {hydrateRoot} from 'react-dom/client';
@@ -131,20 +131,20 @@ hydrateRoot(
131
131
132
132
---
133
133
134
-
### Updating a hydrated root component {/*updating-a-hydrated-root-component*/}
134
+
### Actualización de un componente raíz hidratado {/*updating-a-hydrated-root-component*/}
135
135
136
-
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 dothis because the initial content was already rendered asHTML.**
136
+
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 comoHTML.**
137
137
138
-
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 inthis example are not destructive:
138
+
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:
139
139
140
140
<Sandpack>
141
141
142
142
```html public/index.html
143
143
<!--
144
-
All HTML content inside <div id="root">...</div> was
145
-
generated by rendering <App /> with react-dom/server.
144
+
Todo el contenido HTML dentro de <div id="root">...</div> fue
145
+
generado al renderizar <App /> con react-dom/server.
@@ -169,110 +169,110 @@ export default function App({counter}) {
169
169
return (
170
170
<>
171
171
<h1>Hello, world! {counter}</h1>
172
-
<input placeholder="Type something here" />
172
+
<input placeholder="Escriba algo aquí" />
173
173
</>
174
174
);
175
175
}
176
176
```
177
177
178
178
</Sandpack>
179
179
180
-
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.
180
+
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.
Call `hydrateRoot` to “attach” React to existing HTML that was already rendered by React in a server environment.
188
+
Llama a `hydrateRoot`para "adjuntar" React al HTMLexistente que ya fue renderizado por React en un entorno del servidor.
189
189
190
190
```js
191
191
const domNode = document.getElementById('root');
192
192
const root = hydrateRoot(domNode, reactNode);
193
193
```
194
194
195
-
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.
195
+
React se unirá al HTMLque existe dentro de`domNode`, y se encargará de gestionar el DOMdentro de él. Una aplicación completamente construida con React normalmente sólo tendrá una llamada a `hydrateRoot`con su componente raíz.
196
196
197
-
[See examples above.](#usage)
197
+
[Consulta los ejemplos anteriores.](#usage)
198
198
199
-
#### Parameters {/*parameters*/}
199
+
#### Parámetros {/*parameters*/}
200
200
201
-
* `domNode`: A [DOM element](https://developer.mozilla.org/en-US/docs/Web/API/Element) that was rendered as the root element on the server.
201
+
*`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.
202
202
203
-
* `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 />)`.
203
+
*`reactNode`:El "nodo de React" utilizado para renderizar el HTMLexistente. Normalmente será un trozo de JSXcomo`<App />`que se ha renderizado con un método de `ReactDOM Server`como`renderToPipeableStream(<App />)`.
204
204
205
-
* **optional** `options`: A object contain options for this React root.
205
+
***opcional**`options`:Un objeto que contiene opciones para esta raíz de React.
206
206
207
-
* `onRecoverableError`: optional callback called when React automatically recovers from errors.
208
-
* `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.
207
+
*`onRecoverableError`:*callback* opcional que se llama cuando React se recupera automáticamente de los errores.
208
+
*`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.
209
209
210
-
#### Returns {/*returns*/}
210
+
#### Devuelve {/*returns*/}
211
211
212
-
`hydrateRoot` returns an object with two methods: [`render`](#root-render) and [`unmount`.](#root-unmount)
212
+
`hydrateRoot`devuelve un objeto con dos métodos: [`render`](#root-render) y [`unmount`.](#root-unmount)
213
213
214
-
#### Caveats {/*caveats*/}
214
+
#### Advertencias {/*caveats*/}
215
215
216
-
* `hydrateRoot()` expects the rendered content to be identical with the server-rendered content. You should treat mismatches as bugs and fix them.
217
-
* 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.
218
-
* You'll likely have only one `hydrateRoot`call in your app. If you use a framework, it might dothis call for you.
219
-
*If your app is client-rendered withno HTMLrendered already, using `hydrateRoot()`is not supported. Use [`createRoot()`](/apis/react-dom/client/createRoot) instead.
216
+
*`hydrateRoot()`espera que el contenido renderizado sea idéntico al contenido renderizado por el servidor. Deberías tratar los desajustes como errores y solucionarlos.
217
+
*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.
218
+
*Es probable que sólo tengas una llamada a `hydrateRoot`en tu aplicación. Si utilizas un *framework*, puede que la haga por ti.
219
+
*Si tu aplicación está renderizada en el cliente y no tiene HTMLrenderizado, el uso de `hydrateRoot()`no es válido. Utiliza [`createRoot()`](/apis/react-dom/client/createRoot) en su lugar.
220
220
221
221
---
222
222
223
223
### `root.render(reactNode)` {/*root-render*/}
224
224
225
-
Call `root.render`to update a React component inside a hydrated React root for a browserDOMelement.
225
+
Llama a `root.render`para actualizar un componente de React dentro de una raíz de React hidratada para un elementoDOMdel navegador.
226
226
227
227
```js
228
228
root.render(<App />);
229
229
```
230
230
231
-
React will update `<App />`in the hydrated `root`.
231
+
React actualizará `<App />`en la raíz hidratada (`root`).
232
232
233
-
[See examples above.](#usage)
233
+
[Consulta los ejemplos anteriores.](#usage)
234
234
235
-
#### Parameters {/*root-render-parameters*/}
235
+
#### Parámetros {/*root-render-parameters*/}
236
236
237
-
*`reactNode`:A"React node" that you want to update. This will usually be a piece ofJSXlike`<App />`, but you can also pass a React element constructed with[`createElement()`](/apis/react/createElement), a string, a number, `null`, or`undefined`.
237
+
*`reactNode`:Un "nodo de React" que quieres actualizar. Normalmente será un trozo de JSXcomo`<App />`, pero también puedes pasar un elemento React construido con [`createElement()`.](/apis/react/createElement), un *string*, un número, `null`, o`undefined`.
238
238
239
239
240
-
#### Returns {/*root-render-returns*/}
240
+
#### Devuelve {/*root-render-returns*/}
241
241
242
-
`root.render`returns`undefined`.
242
+
`root.render`devuelve`undefined`.
243
243
244
-
#### Caveats {/*root-render-caveats*/}
244
+
#### Advertencias {/*root-render-caveats*/}
245
245
246
-
*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.
246
+
*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.
247
247
248
248
---
249
249
250
250
### `root.unmount()` {/*root-unmount*/}
251
251
252
-
Call `root.unmount`to destroy a rendered tree inside a React root.
252
+
Llama a `root.unmount`para destruir un árbol renderizado dentro de una raíz de React.
253
253
254
254
```js
255
255
root.unmount();
256
256
```
257
257
258
-
An app fully built with React will usually not have any calls to`root.unmount`.
258
+
Una aplicación completamente construida con React normalmente no tendrá ninguna llamada a`root.unmount`.
259
259
260
-
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.
260
+
Esto es útil mayormente si el nodo DOMde tu raíz de React (o cualquiera de sus ancestros) puede ser eliminado del DOMpor 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.
261
261
262
-
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.
262
+
Al llamar a `root.unmount`se desmontarán todos los componentes de la raíz y se "separará" React del nodo DOMraíz, incluyendo la eliminación de cualquier controlador de eventos o estado en el árbol.
263
263
264
264
265
-
#### Parameters {/*root-unmount-parameters*/}
265
+
#### Parámetros {/*root-unmount-parameters*/}
266
266
267
-
`root.unmount` does not accept any parameters.
267
+
`root.unmount`no acepta ningún parámetro.
268
268
269
269
270
-
#### Returns {/*root-unmount-returns*/}
270
+
#### Devuelve {/*root-unmount-returns*/}
271
271
272
-
`render` returns `null`.
272
+
`render`devuelve`null`.
273
273
274
-
#### Caveats {/*root-unmount-caveats*/}
274
+
#### Advertencias {/*root-unmount-caveats*/}
275
275
276
-
* Calling `root.unmount` will unmount all the components in the tree and "detach" React from the root DOM node.
276
+
*Llamando a `root.unmount`se desmontarán todos los componentes del árbol y se "separará" React del nodo DOMraíz.
277
277
278
-
* 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.
278
+
*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).
0 commit comments