Skip to content

Commit e7ec931

Browse files
translate spanish hydrateRoot. (#584)
* translate spanish hydrateRoot. * Update hydrateRoot.md Co-authored-by: Rainer Martínez Fraga <rmartinezfraga@yandex.com>
1 parent bf06e0d commit e7ec931

File tree

1 file changed

+68
-68
lines changed

1 file changed

+68
-68
lines changed

beta/src/content/apis/react-dom/client/hydrateRoot.md

Lines changed: 68 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ title: hydrateRoot
44

55
<Intro>
66

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)
88

99
```js
1010
const root = hydrateRoot(domNode, reactNode, options?)
@@ -16,30 +16,30 @@ const root = hydrateRoot(domNode, reactNode, options?)
1616
1717
---
1818
19-
## Usage {/*usage*/}
19+
## Uso {/*usage*/}
2020
21-
### Hydrating server-rendered HTML {/*hydrating-server-rendered-html*/}
21+
### Hidratación de HTML renderizado en el servidor {/*hydrating-server-rendered-html*/}
2222
23-
If your app's HTML was generated by [`react-dom/server`](/apis/react-dom/client/createRoot), you need to *hydrate* it on the client.
23+
Si el HTML de tu aplicación fue generado por [`react-dom/server`](/apis/react-dom/client/createRoot), hay que *hidratarlo* en el cliente.
2424
2525
```js [[1, 3, "document.getElementById('root')"], [2, 3, "<App />"]]
2626
import {hydrateRoot} from 'react-dom/client';
2727

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

31-
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.
31+
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.
3232

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 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.
3434

3535
<Sandpack>
3636

3737
```html public/index.html
3838
<!--
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.
4141
-->
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>
4343
```
4444

4545
```js index.js active
@@ -59,7 +59,7 @@ import { useState } from 'react';
5959
export default function App() {
6060
return (
6161
<>
62-
<h1>Hello, world!</h1>
62+
<h1>¡Hola, mundo!</h1>
6363
<Counter />
6464
</>
6565
);
@@ -69,38 +69,38 @@ function Counter() {
6969
const [count, setCount] = useState(0);
7070
return (
7171
<button onClick={() => setCount(count + 1)}>
72-
You clicked me {count} times
72+
Me has hecho clic {count} veces
7373
</button>
7474
);
7575
}
7676
```
7777

7878
</Sandpack>
7979

80-
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)
80+
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)
8181

8282
<Pitfall>
8383

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.
8585

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.
8787

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

90-
* Extra whitespace (like newlines) around the React-generated HTML inside 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 HTML generado 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.
9494

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.
9696

9797
</Pitfall>
9898

9999
---
100100

101-
### Hydrating an entire document {/*hydrating-an-entire-document*/}
101+
### Hidratar un documento completo {/*hydrating-an-entire-document*/}
102102

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):
104104

105105
```js {3,10}
106106
function App() {
@@ -117,7 +117,7 @@ function App() {
117117
}
118118
```
119119

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`:
121121

122122
```js {5}
123123
import {hydrateRoot} from 'react-dom/client';
@@ -131,20 +131,20 @@ hydrateRoot(
131131

132132
---
133133

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*/}
135135

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 do this because the initial content was already rendered as HTML.**
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 como HTML.**
137137

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 in this 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:
139139

140140
<Sandpack>
141141

142142
```html public/index.html
143143
<!--
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.
146146
-->
147-
<div id="root"><h1>Hello, world! <!-- -->0</h1><input placeholder="Type something here"/></div>
147+
<div id="root"><h1>¡Hola, mundo! <!-- -->0</h1><input placeholder="Escriba algo aquí"/></div>
148148
```
149149

150150
```js index.js active
@@ -169,110 +169,110 @@ export default function App({counter}) {
169169
return (
170170
<>
171171
<h1>Hello, world! {counter}</h1>
172-
<input placeholder="Type something here" />
172+
<input placeholder="Escriba algo aquí" />
173173
</>
174174
);
175175
}
176176
```
177177

178178
</Sandpack>
179179

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.
181181

182182

183183
---
184-
## Reference {/*reference*/}
184+
## Referencia {/*reference*/}
185185

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

188-
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 HTML existente que ya fue renderizado por React en un entorno del servidor.
189189

190190
```js
191191
const domNode = document.getElementById('root');
192192
const root = hydrateRoot(domNode, reactNode);
193193
```
194194

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 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.
196196

197-
[See examples above.](#usage)
197+
[Consulta los ejemplos anteriores.](#usage)
198198

199-
#### Parameters {/*parameters*/}
199+
#### Parámetros {/*parameters*/}
200200

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.
202202

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 HTML existente. Normalmente será un trozo de JSX como `<App />` que se ha renderizado con un método de `ReactDOM Server` como `renderToPipeableStream(<App />)`.
204204

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.
206206

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.
209209

210-
#### Returns {/*returns*/}
210+
#### Devuelve {/*returns*/}
211211

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)
213213

214-
#### Caveats {/*caveats*/}
214+
#### Advertencias {/*caveats*/}
215215

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 do this call for you.
219-
* If your app is client-rendered with no HTML rendered 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 HTML renderizado, el uso de `hydrateRoot()` no es válido. Utiliza [`createRoot()`](/apis/react-dom/client/createRoot) en su lugar.
220220

221221
---
222222

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

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

227227
```js
228228
root.render(<App />);
229229
```
230230

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

233-
[See examples above.](#usage)
233+
[Consulta los ejemplos anteriores.](#usage)
234234

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

237-
* `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`.
237+
* `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`.
238238

239239

240-
#### Returns {/*root-render-returns*/}
240+
#### Devuelve {/*root-render-returns*/}
241241

242-
`root.render` returns `undefined`.
242+
`root.render` devuelve `undefined`.
243243

244-
#### Caveats {/*root-render-caveats*/}
244+
#### Advertencias {/*root-render-caveats*/}
245245

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.
247247

248248
---
249249

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

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.
253253

254254
```js
255255
root.unmount();
256256
```
257257

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`.
259259

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 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.
261261

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 DOM raíz, incluyendo la eliminación de cualquier controlador de eventos o estado en el árbol.
263263

264264

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

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

269269

270-
#### Returns {/*root-unmount-returns*/}
270+
#### Devuelve {/*root-unmount-returns*/}
271271

272-
`render` returns `null`.
272+
`render` devuelve `null`.
273273

274-
#### Caveats {/*root-unmount-caveats*/}
274+
#### Advertencias {/*root-unmount-caveats*/}
275275

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 DOM raíz.
277277

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

Comments
 (0)