Skip to content

Commit 5de647c

Browse files
EzequielMonfortecarburo
authored andcommitted
Lists and Keys Translation (#22)
1 parent 08c7793 commit 5de647c

File tree

1 file changed

+43
-44
lines changed

1 file changed

+43
-44
lines changed

content/docs/lists-and-keys.md

Lines changed: 43 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,30 @@
11
---
22
id: lists-and-keys
3-
title: Lists and Keys
3+
title: Listas y keys
44
permalink: docs/lists-and-keys.html
55
prev: conditional-rendering.html
66
next: forms.html
77
---
88

9-
First, let's review how you transform lists in JavaScript.
9+
Primero, vamos a revisar como transformas listas en Javascript.
1010

11-
Given the code below, we use the [`map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) function to take an array of `numbers` and double their values. We assign the new array returned by `map()` to the variable `doubled` and log it:
11+
Dado el código de abajo, usamos la función [`map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) para tomar un array de `numbers` y duplicar sus valores. Asignamos el nuevo array devuelto por `map()` a la variable `doubled` y la mostramos:
1212

1313
```javascript{2}
1414
const numbers = [1, 2, 3, 4, 5];
1515
const doubled = numbers.map((number) => number * 2);
1616
console.log(doubled);
1717
```
1818

19-
This code logs `[2, 4, 6, 8, 10]` to the console.
19+
Este código muestra `[2, 4, 6, 8, 10]` a la consola.
2020

21-
In React, transforming arrays into lists of [elements](/docs/rendering-elements.html) is nearly identical.
21+
En React, transformar arrays en listas de [elementos](/docs/rendering-elements.html) es casi idéntico.
2222

23-
### Rendering Multiple Components
23+
### Renderizado de Múltiples Componentes
2424

25-
You can build collections of elements and [include them in JSX](/docs/introducing-jsx.html#embedding-expressions-in-jsx) using curly braces `{}`.
25+
Puedes hacer colecciones de elementos e [incluirlos en JSX](/docs/introducing-jsx.html#embedding-expressions-in-jsx) usando llaves `{}`.
2626

27-
Below, we loop through the `numbers` array using the JavaScript [`map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) function. We return a `<li>` element for each item. Finally, we assign the resulting array of elements to `listItems`:
27+
Debajo, recorreremos el array `numbers` usando la función [`map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) de Javascript. Devolvemos un elemento `<li>` por cada ítem . Finalmente, asignamos el array de elementos resultante a `listItems`:
2828

2929
```javascript{2-4}
3030
const numbers = [1, 2, 3, 4, 5];
@@ -33,7 +33,7 @@ const listItems = numbers.map((number) =>
3333
);
3434
```
3535

36-
We include the entire `listItems` array inside a `<ul>` element, and [render it to the DOM](/docs/rendering-elements.html#rendering-an-element-into-the-dom):
36+
Incluimos entero el array `listItems` dentro de un elemento `<ul>`, y [lo renderizamos al DOM](/docs/rendering-elements.html#rendering-an-element-into-the-dom):
3737

3838
```javascript{2}
3939
ReactDOM.render(
@@ -42,15 +42,14 @@ ReactDOM.render(
4242
);
4343
```
4444

45-
[**Try it on CodePen**](https://codepen.io/gaearon/pen/GjPyQr?editors=0011)
45+
[**Pruebalo en CodePen**](https://codepen.io/gaearon/pen/GjPyQr?editors=0011)
4646

47-
This code displays a bullet list of numbers between 1 and 5.
47+
Este código muestra una lista de números entre 1 y 5.
4848

49-
### Basic List Component
49+
### Componente Básico de Lista
50+
Usualmente renderizarías listas dentro de un [componente](/docs/components-and-props.html).
5051

51-
Usually you would render lists inside a [component](/docs/components-and-props.html).
52-
53-
We can refactor the previous example into a component that accepts an array of `numbers` and outputs an unordered list of elements.
52+
Podemos refactorizar el ejemplo anterior en un componente que acepte un array de `numbers` e imprima una lista desordenada de elementos.
5453

5554
```javascript{3-5,7,13}
5655
function NumberList(props) {
@@ -70,9 +69,9 @@ ReactDOM.render(
7069
);
7170
```
7271

73-
When you run this code, you'll be given a warning that a key should be provided for list items. A "key" is a special string attribute you need to include when creating lists of elements. We'll discuss why it's important in the next section.
72+
Cuando ejecutes este código, serás advertido que una key debería ser proporcionada para ítems de lista. Una "key" es un atributo especial string que debes incluir al crear listas de elementos. Vamos a discutir por qué esto es importante en la próxima sección.
7473

75-
Let's assign a `key` to our list items inside `numbers.map()` and fix the missing key issue.
74+
Vamos a asignar una `key` a nuestra lista de ítems dentro de `numbers.map()` y arreglar el problema de la falta de key.
7675

7776
```javascript{4}
7877
function NumberList(props) {
@@ -94,11 +93,11 @@ ReactDOM.render(
9493
);
9594
```
9695

97-
[**Try it on CodePen**](https://codepen.io/gaearon/pen/jrXYRR?editors=0011)
96+
[**Pruébalo en CodePen**](https://codepen.io/gaearon/pen/jrXYRR?editors=0011)
9897

9998
## Keys
10099

101-
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity:
100+
Las keys ayudan a React a identificar que ítems han cambiado, son agregados, o son eliminados. Las keys deben ser dadas a los elementos dentro del array para darle a los elementos una identidad estable:
102101

103102
```js{3}
104103
const numbers = [1, 2, 3, 4, 5];
@@ -109,7 +108,7 @@ const listItems = numbers.map((number) =>
109108
);
110109
```
111110

112-
The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys:
111+
La mejor forma de elegir una key es usando un string que idenfique únicamente a un elemento de la lista entre sus hermanos. Habitualmente vas a usar IDs de tus datos como key:
113112

114113
```js{2}
115114
const todoItems = todos.map((todo) =>
@@ -119,7 +118,7 @@ const todoItems = todos.map((todo) =>
119118
);
120119
```
121120

122-
When you don't have stable IDs for rendered items, you may use the item index as a key as a last resort:
121+
Cuando no tengas IDs estables para renderizar, puedes usar el índice del ítem como una key como último recurso:
123122

124123
```js{2,3}
125124
const todoItems = todos.map((todo, index) =>
@@ -130,23 +129,23 @@ const todoItems = todos.map((todo, index) =>
130129
);
131130
```
132131

133-
We don't recommend using indexes for keys if the order of items may change. This can negatively impact performance and may cause issues with component state. Check out Robin Pokorny's article for an [in-depth explanation on the negative impacts of using an index as a key](https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318). If you choose not to assign an explicit key to list items then React will default to using indexes as keys.
132+
No recomendamos usar índices para keys si el orden de los ítems puede cambiar. Esto puede impactar negativamente el rendimiento y puede causar problemas con el estado del componente. Revisa el árticulo de Robin Pokorny para una [explicación en profundidad de los impactos negativos de usar un índice como key](https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318). Si eliges no asignar una key explícita a la lista de ítems, React por defecto usará índices como keys.
134133

135-
Here is an [in-depth explanation about why keys are necessary](/docs/reconciliation.html#recursing-on-children) if you're interested in learning more.
134+
Aquí hay una [explicación en profundidad sobre por qué las keys son necesarias](/docs/reconciliation.html#recursing-on-children) si estás interesado en aprender más.
136135

137-
### Extracting Components with Keys
136+
### Extracción de Componentes con Keys
138137

139-
Keys only make sense in the context of the surrounding array.
138+
Las keys solo tienen sentido en el contexto del array que las envuelve.
140139

141-
For example, if you [extract](/docs/components-and-props.html#extracting-components) a `ListItem` component, you should keep the key on the `<ListItem />` elements in the array rather than on the `<li>` element in the `ListItem` itself.
140+
Por ejemplo, si [extraes](/docs/components-and-props.html#extracting-components) un componente `ListItem`, deberías mantener la key en los elementos `<ListItem />` del array en lugar de en el elemento `<li>` del propio `ListItem`.
142141

143-
**Example: Incorrect Key Usage**
142+
**Ejemplo: Uso Incorrecto de Key**
144143

145144
```javascript{4,5,14,15}
146145
function ListItem(props) {
147146
const value = props.value;
148147
return (
149-
// Wrong! There is no need to specify the key here:
148+
// Mal! No hay necesidad de especificar la key aquí:
150149
<li key={value.toString()}>
151150
{value}
152151
</li>
@@ -156,7 +155,7 @@ function ListItem(props) {
156155
function NumberList(props) {
157156
const numbers = props.numbers;
158157
const listItems = numbers.map((number) =>
159-
// Wrong! The key should have been specified here:
158+
// Mal! La key debería haber sido especificada aquí:
160159
<ListItem value={number} />
161160
);
162161
return (
@@ -173,18 +172,18 @@ ReactDOM.render(
173172
);
174173
```
175174

176-
**Example: Correct Key Usage**
175+
**Ejemplo: Uso Correcto de Key**
177176

178177
```javascript{2,3,9,10}
179178
function ListItem(props) {
180-
// Correct! There is no need to specify the key here:
179+
// Correcto! No hay necesidad de especificar la key aquí:
181180
return <li>{props.value}</li>;
182181
}
183182
184183
function NumberList(props) {
185184
const numbers = props.numbers;
186185
const listItems = numbers.map((number) =>
187-
// Correct! Key should be specified inside the array.
186+
// Correcto! La key debería ser especificada dentro del array.
188187
<ListItem key={number.toString()}
189188
value={number} />
190189
);
@@ -202,13 +201,13 @@ ReactDOM.render(
202201
);
203202
```
204203

205-
[**Try it on CodePen**](https://codepen.io/gaearon/pen/ZXeOGM?editors=0010)
204+
[**Pruébalo en CodePen**](https://codepen.io/gaearon/pen/ZXeOGM?editors=0010)
206205

207-
A good rule of thumb is that elements inside the `map()` call need keys.
206+
Una buena regla es que los elementos dentro de `map()` necesitan keys.
208207

209-
### Keys Must Only Be Unique Among Siblings
208+
### Las Keys Deben Ser Únicas Solo Entre Hermanos
210209

211-
Keys used within arrays should be unique among their siblings. However they don't need to be globally unique. We can use the same keys when we produce two different arrays:
210+
Las keys usadas dentro de arrays deberían ser únicas entre sus hermanos. Sin embargo, no necesitan ser únicas globalmente. Podemos usar las mismas keys cuando creamos dos arrays diferentes:
212211

213212
```js{2,5,11,12,19,21}
214213
function Blog(props) {
@@ -246,9 +245,9 @@ ReactDOM.render(
246245
);
247246
```
248247

249-
[**Try it on CodePen**](https://codepen.io/gaearon/pen/NRZYGN?editors=0010)
248+
[**Pruébalo en CodePen**](https://codepen.io/gaearon/pen/NRZYGN?editors=0010)
250249

251-
Keys serve as a hint to React but they don't get passed to your components. If you need the same value in your component, pass it explicitly as a prop with a different name:
250+
Las keys sirven como una sugerencia para React pero no son pasadas a tus componentes. Si necesitas usar el mismo valor en tu componente, pásasela explícitamente como una propiedad con un nombre diferente:
252251

253252
```js{3,4}
254253
const content = posts.map((post) =>
@@ -259,11 +258,11 @@ const content = posts.map((post) =>
259258
);
260259
```
261260

262-
With the example above, the `Post` component can read `props.id`, but not `props.key`.
261+
Con el ejemplo de arriba, el componente `Post` puede leer `props.id`, pero no `props.key`.
263262

264-
### Embedding map() in JSX
263+
### Integrar map() en JSX
265264

266-
In the examples above we declared a separate `listItems` variable and included it in JSX:
265+
En los ejemplos de arriba declaramos una variable separada `listItems` y la incluimos en JSX:
267266

268267
```js{3-6}
269268
function NumberList(props) {
@@ -280,7 +279,7 @@ function NumberList(props) {
280279
}
281280
```
282281

283-
JSX allows [embedding any expression](/docs/introducing-jsx.html#embedding-expressions-in-jsx) in curly braces so we could inline the `map()` result:
282+
JSX permite [integrar cualquier expresión](/docs/introducing-jsx.html#embedding-expressions-in-jsx) en llaves así que podemos alinear el resultado de `map()`:
284283

285284
```js{5-8}
286285
function NumberList(props) {
@@ -296,6 +295,6 @@ function NumberList(props) {
296295
}
297296
```
298297

299-
[**Try it on CodePen**](https://codepen.io/gaearon/pen/BLvYrB?editors=0010)
298+
[**Pruébalo en CodePen**](https://codepen.io/gaearon/pen/BLvYrB?editors=0010)
300299

301-
Sometimes this results in clearer code, but this style can also be abused. Like in JavaScript, it is up to you to decide whether it is worth extracting a variable for readability. Keep in mind that if the `map()` body is too nested, it might be a good time to [extract a component](/docs/components-and-props.html#extracting-components).
300+
Algunas veces esto resulta en código mas claro, pero este estilo también puede ser abusado. Como en JavaScript, depende de ti decidir cuando vale la pena extraer una variable por legibilidad. Ten en mente que si el cuerpo de `map()` esta muy anidado, puede ser un buen momento para [extraer un componente](/docs/components-and-props.html#extracting-components).

0 commit comments

Comments
 (0)