From 7033cb727b6d30921189fc9cb6e1430406322348 Mon Sep 17 00:00:00 2001 From: luiserdef Date: Sat, 17 Jun 2023 22:43:44 -0500 Subject: [PATCH 01/64] Translate Getting a ref to the node --- .../learn/manipulating-the-dom-with-refs.md | 46 +++++++++---------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/src/content/learn/manipulating-the-dom-with-refs.md b/src/content/learn/manipulating-the-dom-with-refs.md index 3e91a7694..1616f32cf 100644 --- a/src/content/learn/manipulating-the-dom-with-refs.md +++ b/src/content/learn/manipulating-the-dom-with-refs.md @@ -1,52 +1,52 @@ --- -title: 'Manipulating the DOM with Refs' +title: 'Manipulando el DOM con Refs' --- -React automatically updates the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model/Introduction) to match your render output, so your components won't often need to manipulate it. However, sometimes you might need access to the DOM elements managed by React--for example, to focus a node, scroll to it, or measure its size and position. There is no built-in way to do those things in React, so you will need a *ref* to the DOM node. +React automáticamente actualiza el [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model/Introduction) para que coincida con tu salida de renderizado, por lo que tus componentes a menudo no necesitarán manipularlo. Sin embargo, a veces es posible que necesites acceder a los elementos del DOM administrados por React, por ejemplo, enfocar un nodo, desplazarse hasta él, o medir su tamaño y posición. No hay una forma integrada para hacer este tipo de cosas en React, por lo que necesitaras una *ref* al nodo DOM. -- How to access a DOM node managed by React with the `ref` attribute -- How the `ref` JSX attribute relates to the `useRef` Hook -- How to access another component's DOM node -- In which cases it's safe to modify the DOM managed by React +- Cómo acceder a un nodo DOM manipulado por React con el atributo `ref` +- Cómo el atributo `ref` de JSX se relaciona con el Hook `useRef` +- Cómo acceder al nodo DOM de otro componente +- En qué casos es seguro modificar el DOM manipulado por React -## Getting a ref to the node {/*getting-a-ref-to-the-node*/} +## Obteniendo una ref al nodo {/*getting-a-ref-to-the-node*/} -To access a DOM node managed by React, first, import the `useRef` Hook: +Para acceder a un nodo DOM manipulado por React, primero importa el Hook `useRef`: ```js import { useRef } from 'react'; ``` -Then, use it to declare a ref inside your component: +Luego, úsalo para declarar una ref dentro de tu componente ```js const myRef = useRef(null); ``` -Finally, pass your ref as the `ref` attribute to the JSX tag for which you want to get the DOM node: +Finalmente, pasa la ref como el atributo `ref` a la etiqueta JSX en el que quieres obtener el nodo DOM: ```js
``` -The `useRef` Hook returns an object with a single property called `current`. Initially, `myRef.current` will be `null`. When React creates a DOM node for this `
`, React will put a reference to this node into `myRef.current`. You can then access this DOM node from your [event handlers](/learn/responding-to-events) and use the built-in [browser APIs](https://developer.mozilla.org/docs/Web/API/Element) defined on it. +El Hook `useRef` retorna un objeto con una sola propiedad llamada `current`. Inicialmente, `myRef.current` va a ser `null`. Cuando React crea un nodo DOM para este `
`, React va a colocar una referencia de este nodo en `myRef.current`. Entonces ahora puedes acceder a este nodo DOM desde tus [manejadores de eventos](/learn/responding-to-events) y usar las [APIs de navegador](https://developer.mozilla.org/docs/Web/API/Element) integradas definidas en él. ```js -// You can use any browser APIs, for example: +// Puedes usar cualquier API de navegador, por ejemplo: myRef.current.scrollIntoView(); ``` -### Example: Focusing a text input {/*example-focusing-a-text-input*/} +### Ejemplo: Enfocar la entrada de texto {/*example-focusing-a-text-input*/} -In this example, clicking the button will focus the input: +En este ejemplo, hacer click en el botón va a enfocar la entrada de texto: @@ -64,7 +64,7 @@ export default function Form() { <> ); @@ -73,18 +73,18 @@ export default function Form() { -To implement this: +Para implementar esto: -1. Declare `inputRef` with the `useRef` Hook. -2. Pass it as ``. This tells React to **put this ``'s DOM node into `inputRef.current`.** -3. In the `handleClick` function, read the input DOM node from `inputRef.current` and call [`focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) on it with `inputRef.current.focus()`. -4. Pass the `handleClick` event handler to ` ); @@ -376,17 +376,17 @@ export default function MyForm() { -To help you notice the issue, React also prints an error to the console: +Para ayudarte a notar el problema, React también mostrará un error en la consola. -Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()? +Advertencia: A los componentes de función no se les pueden dar refs. Los intentos para acceder a esta ref no funcionará. Querras decir React.forwardRef()? -This happens because by default React does not let a component access the DOM nodes of other components. Not even for its own children! This is intentional. Refs are an escape hatch that should be used sparingly. Manually manipulating _another_ component's DOM nodes makes your code even more fragile. +Esto pasa porque por defecto React no le permite a un componente acceder a los nodos DOM de otros componentes. Ni siquiera para sus propios hijos! Esto es intencional. Las refs son una escotilla de escape que debe usarse con moderación. Manipular manualmente los nodos DOM de _otros_ componentes hace que tu código sea incluso mas frágil. -Instead, components that _want_ to expose their DOM nodes have to **opt in** to that behavior. A component can specify that it "forwards" its ref to one of its children. Here's how `MyInput` can use the `forwardRef` API: +En cambio, los componentes que _quieren_ exponer sus nodos DOM tienen que **optar** por ese comportamiento. Un componente puede especificar que "reenvie" su ref a uno de sus hijos. Aqui vemos como `MyInput` puede usar la API `forwardRef`. ```js const MyInput = forwardRef((props, ref) => { @@ -394,13 +394,13 @@ const MyInput = forwardRef((props, ref) => { }); ``` -This is how it works: +Así es como funciona: -1. `` tells React to put the corresponding DOM node into `inputRef.current`. However, it's up to the `MyInput` component to opt into that--by default, it doesn't. -2. The `MyInput` component is declared using `forwardRef`. **This opts it into receiving the `inputRef` from above as the second `ref` argument** which is declared after `props`. -3. `MyInput` itself passes the `ref` it received to the `` inside of it. +1. `` le dice a React que coloque el nodo DOM correspondiente en `inputRef.current`. Sin embargo, depende del componente `MyInput` utilizarlo o no; por defecto no lo hace. +2. El componente `MyInput` es declarado usando `forwardRef`. **Esto hace que pueda obtar por recibir el `inputRef` como segundo argumento de `ref`** la cual está declarada después de `props`. +3. `MyInput` por si mismo pasa la `ref` que recibió del `` dentro de él. -Now clicking the button to focus the input works: +Ahora al hacer clic en el botón para enfocar la entrada de texto, funciona: @@ -422,7 +422,7 @@ export default function Form() { <> ); @@ -431,13 +431,14 @@ export default function Form() { -In design systems, it is a common pattern for low-level components like buttons, inputs, and so on, to forward their refs to their DOM nodes. On the other hand, high-level components like forms, lists, or page sections usually won't expose their DOM nodes to avoid accidental dependencies on the DOM structure. +En diseño de sistemas, es un patrón común para componentes de bajo nivel como botones, entradas, etc, reenviar sus refs a sus nodos DOM. +Por otra parte, componentes de alto nivel como formularios, listas, o secciones de pagina, usualmente no exponen sus nodos DOM para evitar dependencias accidentales en la estructura del DOM. -#### Exposing a subset of the API with an imperative handle {/*exposing-a-subset-of-the-api-with-an-imperative-handle*/} +#### Exponiendo un subconjunto de la API con un manejador {/*exposing-a-subset-of-the-api-with-an-imperative-handle*/} -In the above example, `MyInput` exposes the original DOM input element. This lets the parent component call `focus()` on it. However, this also lets the parent component do something else--for example, change its CSS styles. In uncommon cases, you may want to restrict the exposed functionality. You can do that with `useImperativeHandle`: +En el ejemplo de arriba, `MyInput` expone el elemento de entrada DOM orignal. Esto le permite al componente padre llamar a `focus()` en él. Sin embargo, esto tambien le permite al componente padre hacer otra cosa, por ejemplo, cambiar sus estilos CSS. En casos pocos comunes, quizas quieras restringir la funcionalidad expuesta. Puedes hacer eso con `useImperativeHandle`: @@ -451,7 +452,7 @@ import { const MyInput = forwardRef((props, ref) => { const realInputRef = useRef(null); useImperativeHandle(ref, () => ({ - // Only expose focus and nothing else + // Solo expone focus y nada más focus() { realInputRef.current.focus(); }, @@ -470,7 +471,7 @@ export default function Form() { <> ); @@ -479,7 +480,7 @@ export default function Form() { -Here, `realInputRef` inside `MyInput` holds the actual input DOM node. However, `useImperativeHandle` instructs React to provide your own special object as the value of a ref to the parent component. So `inputRef.current` inside the `Form` component will only have the `focus` method. In this case, the ref "handle" is not the DOM node, but the custom object you create inside `useImperativeHandle` call. +Aquí, `realInputRef` dentro de `MyInput` mantiene el nodo DOM de input actual. Sin embargo, `useImperativeHandle` indica a React a proveer tu propio objeto especial como el valor de una ref al componente padre. Por lo tanto, `inputRef.current` dentro del componente `Form` solo va a tener el método `focus`. En este caso, el "manejador" ref no es el nodo DOM, sino el objeto personalizado que creaste dentro de la llamada de `useImperativeHandle`. From f6afc9ad3b40a183e6d9b351960fd31db03b6279 Mon Sep 17 00:00:00 2001 From: luiserdef Date: Sat, 8 Jul 2023 22:07:03 -0500 Subject: [PATCH 04/64] Translate When React attaches the refs --- .../learn/manipulating-the-dom-with-refs.md | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/src/content/learn/manipulating-the-dom-with-refs.md b/src/content/learn/manipulating-the-dom-with-refs.md index 00b4f6b92..babe6c452 100644 --- a/src/content/learn/manipulating-the-dom-with-refs.md +++ b/src/content/learn/manipulating-the-dom-with-refs.md @@ -436,7 +436,7 @@ Por otra parte, componentes de alto nivel como formularios, listas, o secciones -#### Exponiendo un subconjunto de la API con un manejador {/*exposing-a-subset-of-the-api-with-an-imperative-handle*/} +#### Exponiendo un subconjunto de la API con un manejador imperativo {/*exposing-a-subset-of-the-api-with-an-imperative-handle*/} En el ejemplo de arriba, `MyInput` expone el elemento de entrada DOM orignal. Esto le permite al componente padre llamar a `focus()` en él. Sin embargo, esto tambien le permite al componente padre hacer otra cosa, por ejemplo, cambiar sus estilos CSS. En casos pocos comunes, quizas quieras restringir la funcionalidad expuesta. Puedes hacer eso con `useImperativeHandle`: @@ -484,24 +484,24 @@ Aquí, `realInputRef` dentro de `MyInput` mantiene el nodo DOM de input actual. -## When React attaches the refs {/*when-react-attaches-the-refs*/} +## Cuando React adjunta las refs {/*when-react-attaches-the-refs*/} -In React, every update is split in [two phases](/learn/render-and-commit#step-3-react-commits-changes-to-the-dom): +En React, cada actualización está dividida en [dos fases](/learn/render-and-commit#step-3-react-commits-changes-to-the-dom): -* During **render,** React calls your components to figure out what should be on the screen. -* During **commit,** React applies changes to the DOM. +* Durante el **renderizado,** React llama a tus componentes para averiguar que deberia estar en la pantalla. +* Durante el **commit,** React aplica los cambios a el DOM. -In general, you [don't want](/learn/referencing-values-with-refs#best-practices-for-refs) to access refs during rendering. That goes for refs holding DOM nodes as well. During the first render, the DOM nodes have not yet been created, so `ref.current` will be `null`. And during the rendering of updates, the DOM nodes haven't been updated yet. So it's too early to read them. +En general, [no quieres](/learn/referencing-values-with-refs#best-practices-for-refs) acceder a las refs durante el renderizado. Eso va también para las refs que tienen nodos DOM. Durante el primer renderizado, los nodos DOM aún no han sido creados, entonces `ref.current` será `null`. Y durante el renderizado de actualizaciones, los nodos DOM aun no se han actualizados. Es muy temprano para leerlos. -React sets `ref.current` during the commit. Before updating the DOM, React sets the affected `ref.current` values to `null`. After updating the DOM, React immediately sets them to the corresponding DOM nodes. +React establece `ref.current` durante el commit. Antes de actualizar el DOM, React establece los valores afectados de `ref.current` a null. Después de actualizar el DOM, React inmediatamente los establece en los nodos DOM correspondientes. -**Usually, you will access refs from event handlers.** If you want to do something with a ref, but there is no particular event to do it in, you might need an Effect. We will discuss effects on the next pages. +**Generalmente, vas a acceder a las refs desde los manejadores de eventos.** Si quieres hacer algo con una ref, pero no hay un evento en particular para hacerlo, es posible que necesites un Efecto. Discutiremos los efectos en las próximas páginas. -#### Flushing state updates synchronously with flushSync {/*flushing-state-updates-synchronously-with-flush-sync*/} +#### Vaciando actualizaciones de estado sincrónicamente con flushSync {/*flushing-state-updates-synchronously-with-flush-sync*/} -Consider code like this, which adds a new todo and scrolls the screen down to the last child of the list. Notice how, for some reason, it always scrolls to the todo that was *just before* the last added one: +Considere un código como el siguiente, que añade un nuevo todo y desplaza la pantalla hasta el último hijo de la lista. Nota cómo, por alguna razón, siempre se desplaza hacia el todo que hay *justo antes* del último que se ha añadido. @@ -528,7 +528,7 @@ export default function TodoList() { return ( <> -The issue is with these two lines: +El problema está en estas dos lineas: ```js setTodos([ ...todos, newTodo]); listRef.current.lastChild.scrollIntoView(); ``` -In React, [state updates are queued.](/learn/queueing-a-series-of-state-updates) Usually, this is what you want. However, here it causes a problem because `setTodos` does not immediately update the DOM. So the time you scroll the list to its last element, the todo has not yet been added. This is why scrolling always "lags behind" by one item. +En React, [las actualizaciones de estados se ponen en cola.](/learn/queueing-a-series-of-state-updates) Generalmente, esto es lo que quieres. Sin embargo, aquí causa un problema porque `setTodos` no actualiza el DOM inmediatamente. Entonces, en el momento en el que desplazas la lista al último elemento, el todo aún no ha sido añadido. Esta es la razón por la que al desplazarse siempre se "retrasa" en un elemento. + +Para arreglar este problema, puedes forzar a React a actualizar ("flush") el DOM sincronicamente. Para hacer esto, importa `flushSync` del `react-dom` y **envuelve el actualizador de estado** dentro de una llamada a `flushSync`: -To fix this issue, you can force React to update ("flush") the DOM synchronously. To do this, import `flushSync` from `react-dom` and **wrap the state update** into a `flushSync` call: ```js flushSync(() => { @@ -572,8 +573,7 @@ flushSync(() => { }); listRef.current.lastChild.scrollIntoView(); ``` - -This will instruct React to update the DOM synchronously right after the code wrapped in `flushSync` executes. As a result, the last todo will already be in the DOM by the time you try to scroll to it: +Esto le indicará a React que actualice el DOM sincrónicamente justo después que el código envuelto en `flushSync` se ejecute. Como resultado, el último todo ya estará en el DOM en el momento que intentes desplazarte hacia él. @@ -603,7 +603,7 @@ export default function TodoList() { return ( <> Date: Sat, 8 Jul 2023 23:29:40 -0500 Subject: [PATCH 05/64] Translate Best practices for DOM manipulation with refs --- .../learn/manipulating-the-dom-with-refs.md | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/src/content/learn/manipulating-the-dom-with-refs.md b/src/content/learn/manipulating-the-dom-with-refs.md index babe6c452..815f6a3a8 100644 --- a/src/content/learn/manipulating-the-dom-with-refs.md +++ b/src/content/learn/manipulating-the-dom-with-refs.md @@ -632,15 +632,15 @@ for (let i = 0; i < 20; i++) { -## Best practices for DOM manipulation with refs {/*best-practices-for-dom-manipulation-with-refs*/} +## Mejores prácticas para la manipulación del DOM con refs {/*best-practices-for-dom-manipulation-with-refs*/} -Refs are an escape hatch. You should only use them when you have to "step outside React". Common examples of this include managing focus, scroll position, or calling browser APIs that React does not expose. +Las refs son una escotilla de escape. Deberias usarlo solo cuando tengas que "salir de React". Ejemplos comunes de esto incluye manipular el enfoque, posición de desplazamiento, o llamar a las APIs del navegador que React no expone. -If you stick to non-destructive actions like focusing and scrolling, you shouldn't encounter any problems. However, if you try to **modify** the DOM manually, you can risk conflicting with the changes React is making. +Si te limitas a acciones no destructivas como enfocar o desplazarte, no deberias encontrar ningún problema. Sin embargo, si intentas **modificar** el DOM manualmente, puedes arriesgarte a entrar en conflicto con los cambios que React está haciendo. -To illustrate this problem, this example includes a welcome message and two buttons. The first button toggles its presence using [conditional rendering](/learn/conditional-rendering) and [state](/learn/state-a-components-memory), as you would usually do in React. The second button uses the [`remove()` DOM API](https://developer.mozilla.org/en-US/docs/Web/API/Element/remove) to forcefully remove it from the DOM outside of React's control. +Para ilustrar este problema, este ejemplo incluye un mensaje de bienvenida y dos botones. El primer botón alterna su presencia usando [renderizado condicional](/learn/conditional-rendering) y [estado](/learn/state-a-components-memory), como normalmente lo harias en React. El segundo botón usa el [DOM API `remove()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/remove) para eliminarlo forzadamente del DOM fuera del control de React. -Try pressing "Toggle with setState" a few times. The message should disappear and appear again. Then press "Remove from the DOM". This will forcefully remove it. Finally, press "Toggle with setState": +Intenta presionar "Alternar con setState" unas cuantas veces. El mensaje debe desaparecer y aparecer otra vez. Luego presiona "Eliminar del DOM". Esto lo eliminará forzadamente. Finalmente, presiona "Alternar con setState": @@ -657,15 +657,15 @@ export default function Counter() { onClick={() => { setShow(!show); }}> - Toggle with setState + Alternar con setState - {show &&

Hello world

} + {show &&

Hola Mundo

}
); } @@ -681,20 +681,20 @@ button { -After you've manually removed the DOM element, trying to use `setState` to show it again will lead to a crash. This is because you've changed the DOM, and React doesn't know how to continue managing it correctly. +Después de que hayas eliminado el elemento DOM, intentar usar `setState` para mostrarlo de nuevo provocará un bloqueo, que no funcione. Esto se debe a que has cambiado el DOM, y React no sabe como continuar manejándolo correctamente. -**Avoid changing DOM nodes managed by React.** Modifying, adding children to, or removing children from elements that are managed by React can lead to inconsistent visual results or crashes like above. +**Evita cambiar nodos DOM que React manipula.** Modificar, agregar hijos, o eliminar hijos de elementos que son manipulados por React pueden traer resultados inconcistentes visuales o bloqueos como el de arriba. -However, this doesn't mean that you can't do it at all. It requires caution. **You can safely modify parts of the DOM that React has _no reason_ to update.** For example, if some `
` is always empty in the JSX, React won't have a reason to touch its children list. Therefore, it is safe to manually add or remove elements there. +Sin embargo, esto no quiere decir que no puedas en absoluto. Requiere de cuidado. **Puedes modificar de manera segura partes del DOM que React _no tenga motivos_ para actualizar.** Por ejemplo, si algún `
` siempre está vacío en el JSX, React no tendrá un motivo para tocar su lista de elementos hijos. Por lo tanto, es seguro agregar o eliminar manualmente elementos allí. -- Refs are a generic concept, but most often you'll use them to hold DOM elements. -- You instruct React to put a DOM node into `myRef.current` by passing `
`. -- Usually, you will use refs for non-destructive actions like focusing, scrolling, or measuring DOM elements. -- A component doesn't expose its DOM nodes by default. You can opt into exposing a DOM node by using `forwardRef` and passing the second `ref` argument down to a specific node. -- Avoid changing DOM nodes managed by React. -- If you do modify DOM nodes managed by React, modify parts that React has no reason to update. +- Las refs son un concepto genérico, pero a menudo lo vas a usar para contener elementos DOM. +- Tú le indicas a React a poner un nodo DOM dentro de `myRef.current` pasándole `
`. +- Normalmente, vas a usar las refs para acciones no destructivas como enfocar, desplazar, o medir elementos DOM. +- Un componente no expone sus nodos DOM por defecto. Puede optar por exponer un nodo DOM usando `forwardRef` y pasando el segundo argumento `ref` a un nodo específico. +- Evita cambiar nodos DOM manipulados por React. +- Si modificas nodos DOM manipulados por React, modifica las partes en donde React no tenga motivos para actualizar. From f6d2de8a02a514ccb2aec37fc6a56dbe5aa365ae Mon Sep 17 00:00:00 2001 From: luiserdef Date: Sun, 9 Jul 2023 00:38:31 -0500 Subject: [PATCH 06/64] Translate challenges --- .../learn/manipulating-the-dom-with-refs.md | 56 +++++++++---------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/src/content/learn/manipulating-the-dom-with-refs.md b/src/content/learn/manipulating-the-dom-with-refs.md index 815f6a3a8..616e13a47 100644 --- a/src/content/learn/manipulating-the-dom-with-refs.md +++ b/src/content/learn/manipulating-the-dom-with-refs.md @@ -702,9 +702,9 @@ Sin embargo, esto no quiere decir que no puedas en absoluto. Requiere de cuidado -#### Play and pause the video {/*play-and-pause-the-video*/} +#### Reproduce y pausa el video {/*play-and-pause-the-video*/} -In this example, the button toggles a state variable to switch between a playing and a paused state. However, in order to actually play or pause the video, toggling state is not enough. You also need to call [`play()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play) and [`pause()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/pause) on the DOM element for the `