Skip to content

Commit

Permalink
Translate cloneElement
Browse files Browse the repository at this point in the history
  • Loading branch information
bcentdev committed Nov 12, 2022
1 parent a9bc77a commit 3020065
Showing 1 changed file with 51 additions and 51 deletions.
102 changes: 51 additions & 51 deletions beta/src/content/apis/react/cloneElement.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ title: cloneElement

<Pitfall>

Using `cloneElement` is uncommon and can lead to fragile code. [See common alternatives.](#alternatives)
El uso de `cloneElement` no es común y puede conducir a un código frágil. [Mira alternativas comunes.](#alternatives)

</Pitfall>

<Intro>

`cloneElement` lets you create a new React element using another element as a starting point.
`cloneElement` te permite crear un nuevo elemento de React usando otro elemento como punto de partida.

```js
const clonedElement = cloneElement(element, props, ...children)
Expand All @@ -22,11 +22,11 @@ const clonedElement = cloneElement(element, props, ...children)

---

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

### Overriding props of an element {/*overriding-props-of-an-element*/}
### Sobreescribiendo propiedades de un elemento {/*overriding-props-of-an-element*/}

To override the props of some <CodeStep step={1}>React element</CodeStep>, pass it to `cloneElement` with the <CodeStep step={2}>props you want to override</CodeStep>:
Para sobreescribir las propiedades de algún <CodeStep step={1}>React element</CodeStep>, pásalo a `cloneElement` con las <CodeStep step={2}>propiedades que quieres sobreescribir</CodeStep>:

```js [[1, 5, "<Row title=\\"Cabbage\\" />"], [2, 6, "{ isHighlighted: true }"], [3, 4, "clonedElement"]]
import { cloneElement } from 'react';
Expand All @@ -38,11 +38,11 @@ const clonedElement = cloneElement(
);
```

Here, the resulting <CodeStep step={3}>cloned element</CodeStep> will be `<Row title="Cabbage" isHighlighted={true} />`.
Aquí, el <CodeStep step={3}>elemento clonado</CodeStep> resultante será `<Row title="Cabbage" isHighlighted={true} />`.

**Let's walk through an example to see when it's useful.**
**Veamos un ejemplo para ver cuándo es útil.**

Imagine a `List` component that renders its [`children`](/learn/passing-props-to-a-component#passing-jsx-as-children) as a list of selectable rows with a "Next" button that changes which row is selected. The `List` component needs to render the selected `Row` differently, so it clones every `<Row>` child that it has received, and adds an extra `isHighlighted: true` or `isHighlighted: false` prop:
Imagina un componente `List` que renderiza sus [`children`](/learn/passing-props-to-a-component#passing-jsx-as-children) como una lista de filas seleccionables con un botón "Next" que cambia qué fila está seleccionada. El componente `List` necesita renderizar la `Row` seleccionada de manera diferente, por lo que clona cada hijo `<Row>` que ha recibido y agrega una propiedad extra `isHighlighted: true` o `isHighlighted: false`:

```js {6-8}
export default function List({ children }) {
Expand All @@ -56,7 +56,7 @@ export default function List({ children }) {
)}
```
Let's say the original JSX received by `List` looks like this:
Digamos que el JSX original recibido por `List` se ve así:
```js {2-4}
<List>
Expand All @@ -66,7 +66,7 @@ Let's say the original JSX received by `List` looks like this:
</List>
```
By cloning its children, the `List` can pass extra information to every `Row` inside. The result looks like this:
Clonando sus hijos, `List` puede pasar información adicional a cada `Row` dentro. El resultado se ve así:
```js {4,8,12}
<List>
Expand All @@ -85,7 +85,7 @@ By cloning its children, the `List` can pass extra information to every `Row` in
</List>
```
Notice how pressing "Next" updates the state of the `List`, and highlights a different row:
Observe cómo al presionar "Next" actualiza el estado del `List`, y resalta una fila diferente:
<Sandpack>
Expand Down Expand Up @@ -180,21 +180,21 @@ button {
</Sandpack>
To summarize, the `List` cloned the `<Row />` elements it received and added an extra prop to them.
Para resumir, `List` clonó los elementos `<Row />` que recibió y les agregó una propiedad extra.
<Pitfall>
Cloning children makes it hard to tell how the data flows through your app. Try one of the [alternatives.](#alternatives)
Clonando los hijos hace difícil saber cómo fluye la información a través de tu aplicación. Intenta una de las [alternativas](#alternatives).
</Pitfall>
---
## Alternatives {/*alternatives*/}
## Alternativas {/*alternatives*/}
### Passing data with a render prop {/*passing-data-with-a-render-prop*/}
### Pasando datos con una render prop {/*passing-data-with-a-render-prop*/}
Instead of using `cloneElement`, consider accepting a *render prop* like `renderItem`. Here, `List` receives `renderItem` as a prop. `List` calls `renderItem` for every item and passes `isHighlighted` as an argument:
En vez de usar `cloneElement`, considera aceptar una *render prop* como `renderItem`. Aquí, `List` recibe `renderItem` como una propiedad. `List` llama a `renderItem` para cada elemento y pasa `isHighlighted` como un argumento:
```js {1,7}
export default function List({ items, renderItem }) {
Expand All @@ -207,7 +207,7 @@ export default function List({ items, renderItem }) {
})}
```
The `renderItem` prop is called a "render prop" because it's a prop that specifies how to render something. For example, you can pass a `renderItem` implementation that renders a `<Row>` with the given `isHighlighted` value:
La propiedad `renderItem` se llama una "render prop" porque es una propiedad que especifica cómo renderizar algo. Por ejemplo, puedes pasar una implementación de `renderItem` que renderice un `<Row>` con el valor `isHighlighted` dado:
```js {3,7}
<List
Expand All @@ -222,7 +222,7 @@ The `renderItem` prop is called a "render prop" because it's a prop that specifi
/>
```
The end result is the same as with `cloneElement`:
El resultado final es el mismo que con `cloneElement`:
```js {4,8,12}
<List>
Expand All @@ -241,7 +241,7 @@ The end result is the same as with `cloneElement`:
</List>
```
However, you can clearly trace where the `isHighlighted` value is coming from.
Sin embargo, puedes rastrear claramente de dónde viene el valor `isHighlighted`.
<Sandpack>
Expand Down Expand Up @@ -337,22 +337,22 @@ button {
</Sandpack>
This pattern is preferred to `cloneElement` because it is more explicit.
Este patrón es preferido a `cloneElement` porque es más explícito.
---
### Passing data through context {/*passing-data-through-context*/}
### Pasando datos a través del contexto {/*passing-data-through-context*/}
Another alternative to `cloneElement` is to [pass data through context.](/learn/passing-data-deeply-with-context)
Otra alternativa a `cloneElement` es [pasar datos a través del contexto.](/learn/passing-data-deeply-with-context)
For example, you can call [`createContext`](/apis/react/createContext) to define a `HighlightContext`:
Por ejemplo, puedes llamar a [`createContext`](/apis/react/createContext) para definir un `HighlightContext`:
```js
export const HighlightContext = createContext(false);
```
Your `List` component can wrap every item it renders into a `HighlightContext` provider:
Tu componente `List` puede envolver cada elemento que renderiza en un proveedor de `HighlightContext`:
```js {8,10}
export default function List({ items, renderItem }) {
Expand All @@ -369,15 +369,15 @@ export default function List({ items, renderItem }) {
})}
```
With this approach, `Row` does not need to receive an `isHighlighted` prop at all. Instead, it reads the context:
Con este enfoque, `Row` no necesita recibir una propiedad `isHighlighted` en absoluto. En su lugar, lee el contexto:
```js Row.js {2}
export default function Row({ title }) {
const isHighlighted = useContext(HighlightContext);
// ...
````

This allows the calling component to not know or worry about passing `isHighlighted` to `<Row>`:
Esto permite que el componente que llama no sepa o se preocupe por pasar `isHighlighted` a `<Row>`:

```js {4}
<List
Expand All @@ -388,7 +388,7 @@ This allows the calling component to not know or worry about passing `isHighligh
/>
```

Instead, `List` and `Row` coordinate the highlighting logic through context.
En vez de eso, `List` y `Row` coordinan la lógica de resaltado a través del contexto.

<Sandpack>

Expand Down Expand Up @@ -498,13 +498,13 @@ button {

</Sandpack>

[Learn more about passing data through context.](/apis/react/useContext#passing-data-deeply-into-the-tree)
[Aprende más sobre pasar datos a través del contexto.](/apis/react/useContext#passing-data-deeply-into-the-tree)

---

### Extracting logic into a custom Hook {/*extracting-logic-into-a-custom-hook*/}
### Extrayendo lógica en un Hook personalizado {/*extracting-logic-into-a-custom-hook*/}

Another approach you can try is to extract the "non-visual" logic into your own Hook, and use the information returned by your Hook to decide what to render. For example, you could write a `useList` custom Hook like this:
Otro enfoque que puedes probar es extraer la lógica "no visual" en tu propio Hook, y usar la información devuelta por tu Hook para decidir qué renderizar. Por ejemplo, puedes escribir un Hook personalizado `useList` como este:

```js
import { useState } from 'react';
Expand All @@ -523,7 +523,7 @@ export default function useList(items) {
}
```

Then you could use it like this:
Entonces puedes usarlo así:

```js {2,9,13}
export default function App() {
Expand All @@ -546,7 +546,7 @@ export default function App() {
}
```

The data flow is explicit, but the state is inside the `useList` custom Hook that you can use from any component:
El flujo de datos es explícito, pero el estado está dentro del Hook personalizado `useList` que puedes usar desde cualquier componente:

<Sandpack>

Expand Down Expand Up @@ -639,15 +639,15 @@ button {

</Sandpack>

This approach is particularly useful if you want to reuse this logic between different components.
Este enfoque es particularmente útil si quieres reutilizar esta lógica entre diferentes componentes.

---

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

### `cloneElement(element, props, ...children)` {/*cloneelement*/}

Call `cloneElement` to create a React element based on the `element`, but with different `props` and `children`:
Llama a `cloneElement` para crear un elemento React basado en el `element`, pero con diferentes `props` y `children`:

```js
import { cloneElement } from 'react';
Expand All @@ -664,31 +664,31 @@ const clonedElement = cloneElement(
console.log(clonedElement); // <Row title="Cabbage">Goodbye</Row>
```

[See more examples above.](#usage)
[Ver más ejemplos arriba.](#usage)

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

* `element`: The `element` argument must be a valid React element. For example, it could be a JSX node like `<Something />`, the result of calling [`createElement`](/apis/react/createElement), or the result of another `cloneElement` call.
* `element`: El argumento `element` debe ser un elemento React lido. Por ejemplo, podría ser un nodo JSX como `<Something />`, el resultado de llamar a [`createElement`](/apis/react/createElement), o el resultado de otra llamada a `cloneElement`.

* `props`: The `props` argument must either be an object or `null`. If you pass `null`, the cloned element will retain all of the original `element.props`. Otherwise, for every prop in the `props` object, the returned element will "prefer" the value from `props` over the value from `element.props`. The rest of the props will be filled from the original `element.props`. If you pass `props.key` or `props.ref`, they will replace the original ones.
* `props`: El argumento `props` debe ser un objeto o `null`. Si pasas `null`, el elemento clonado mantendrá todos los `element.props` originales. De lo contrario, para cada propiedad en el objeto `props`, el elemento devuelto "preferirá" el valor de `props` sobre el valor de `element.props`. El resto de las propiedades se completarán a partir de los `element.props` originales. Si pasas `props.key` o `props.ref`, reemplazarán a los originales.

* **optional** `...children`: Zero or more child nodes. They can be any React nodes, including React elements, strings, numbers, [portals](/apis/react-dom/createPortal), empty nodes (`null`, `undefined`, `true`, and `false`), and arrays of React nodes. If you don't pass any `...children` arguments, the original `element.props.children` will be preserved.
* **opcional** `...children`: Cero o más nodos hijo. Pueden ser cualquier nodo React, incluidos elementos React, cadenas, números, [portales](/apis/react-dom/createPortal), nodos vacíos (`null`, `undefined`, `true`, y `false`), y matrices de nodos React. Si no pasas ningún argumento `...children`, se conservarán los `element.props.children` originales.

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

`cloneElement` returns a React element object with a few properties:
`cloneElement` devuelve un objeto de elemento React con algunas propiedades:

* `type`: Same as `element.type`.
* `props`: The result of shallowly merging `element.props` with the overriding `props` you have passed.
* `ref`: The original `element.ref`, unless it was overridden by `props.ref`.
* `key`: The original `element.key`, unless it was overridden by `props.key`.
* `type`: Igual que `element.type`.
* `props`: El resultado de mezclar superficialmente `element.props` con los `props` que has pasado para sobrescribirlos.
* `ref`: El `element.ref` original, a menos que se haya anulado con `props.ref`.
* `key`: El `element.key` original, a menos que se haya anulado con `props.key`.

Usually, you'll return the element from your component or make it a child of another element. Although you may read the element's properties, it's best to treat every element as opaque after it's created, and only render it.
Usualmente, devolverás el elemento desde tu componente o lo harás hijo de otro elemento. Aunque puedes leer las propiedades del elemento, es mejor tratar a cada elemento como opaco después de que se crea, y solo renderizarlo.

#### Caveats {/*caveats*/}
#### Advertencias {/*advertencias*/}

* Cloning an element **does not modify the original element.**
* Clonar un elemento **no modifica el elemento original.**

* You should only **pass children as multiple arguments to `createElement` if they are all statically known,** like `cloneElement(element, null, child1, child2, child3)`. If your children are dynamic, pass the entire array as the third argument: `cloneElement(element, null, listItems)`. This ensures that React will [warn you about missing `key`s](/learn/rendering-lists#keeping-list-items-in-order-with-key) for any dynamic lists. For static lists this is not necessary because they never reorder.
* Solo debes **pasar hijos como múltiples argumentos a `createElement` si todos son conocidos estáticamente**, como `cloneElement(element, null, child1, child2, child3)`. Si tus hijos son dinámicos, pasa toda la matriz como tercer argumento: `cloneElement(element, null, listItems)`. Esto garantiza que React te [advertirá sobre las `key`s que faltan](/learn/rendering-lists#keeping-list-items-in-order-with-key) para cualquier lista dinámica. Para listas estáticas no es necesario porque nunca se reordenan.

* `cloneElement` makes it harder to trace the data flow, so **try the [alternatives](/#alternatives) instead.**
* `cloneElement` hace que sea más difícil rastrear el flujo de datos, por lo que **intente las [alternativas](/#alternatives) en su lugar.**

0 comments on commit 3020065

Please sign in to comment.