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/pages/learn/writing-markup-with-jsx.md
+43-42Lines changed: 43 additions & 42 deletions
Original file line number
Diff line number
Diff line change
@@ -1,24 +1,24 @@
1
1
---
2
-
title: Writing Markup with JSX
2
+
title: Escribir marcado con JSX
3
3
---
4
4
5
5
<Intro>
6
6
7
-
JSX is a syntax extension for JavaScript that lets you write HTML-like markup inside a JavaScript file. Although there are other ways to write components, most React developers prefer the conciseness of JSX, and most codebases use it.
7
+
JSX es una extensión de sintaxis para JavaScript que permite escribir marcas similares a HTML dentro de una archivo JavaScript. Aunque hay otras formas de escribir componentes, la mayoría de los desarrolladores de React prefieren la concisión de JSX, y la mayoría de las bases de código lo usan.
8
8
9
9
</Intro>
10
10
11
11
<YouWillLearn>
12
12
13
-
*Why React mixes markup with rendering logic
14
-
*How JSX is different from HTML
15
-
*How to display information with JSX
13
+
*Por qué React mezcla marcado con lógica de renderizado
14
+
*En qué se diferencia JSX de HTML
15
+
*Cómo mostrar información con JSX
16
16
17
17
</YouWillLearn>
18
18
19
-
## JSX: Putting markup into JavaScript {/*jsx-putting-markup-into-javascript*/}
19
+
## JSX: Poniendo marcado dentro de JavaScript {/*jsx-putting-markup-into-javascript*/}
20
20
21
-
The Web has been built on HTML, CSS, and JavaScript. For many years, web developers kept content in HTML, design in CSS, and logic in JavaScript—often in separate files! Content was marked up inside HTML while the page's logic lived separately in JavaScript:
21
+
La Web se ha construido sobre HTML, CSS, y JavaScript. Durante muchos años, los desarrolladores web mantuvieron el contenido en HTML, el diseño en CSS, y la lógica en JavaScript, ¡a menudo en archivos separados! El contenido se marcó dentro del HTML mientras que la lógica de la pagina vivía por separado en JavaScript:
22
22
23
23
<DiagramGroup>
24
24
@@ -36,7 +36,7 @@ JavaScript
36
36
37
37
</DiagramGroup>
38
38
39
-
But as the Web became more interactive, logic increasingly determined content. JavaScript was in charge of the HTML! This is why **in React, rendering logic and markup live together in the same place—components!**
39
+
Pero, a medida que la Web se volvió más interactiva, la lógica determinó cada vez más el contenido. ¡JavaScript estaba a cargo del HTML! Esto es la razón por la que **en React, la lógica de renderizado y el marcado viven juntos en el mismo lugar: ¡componentes!**
40
40
41
41
<DiagramGroup>
42
42
@@ -54,19 +54,20 @@ Form.js
54
54
55
55
</DiagramGroup>
56
56
57
-
Keeping a button's rendering logic and markup together ensures that they stay in sync with each other on every edit. Conversely, details that are unrelated, such as the button's markup and a sidebar's markup, are isolated from each other, making it safer to change either of them on their own.
57
+
Mantener juntas la lógica de renderizado y el marcado de un botón, garantiza que permanezcan sincronizados entre sí en cada edición. Por el contrario, los detalles que no están relacionados, como el marcado de un botón y el marcado de una barra lateral, están aislados entre sí, haciendo que sea más seguro cambiar cualquiera de ellos por su cuenta.
58
58
59
-
Each React component is a JavaScript function that may contain some markup that React renders into the browser. React components use a syntax extension called JSX to represent that markup. JSX looks a lot like HTML, but it is a bit stricter and can display dynamic information. The best way to understand this is to convert some HTML markup to JSX markup.
59
+
Cada componente de React es una función de JavaScript que puede contener algún marcado que React muestra en el navegador. Los componentes de React usan una extensión de sintaxis llamada JSX para representar el marcado. JSX se parece mucho a HTML, pero es un poco más estricto y puede mostrar información dinámica. La mejor manera de comprender esto es convertir algunas marcas HTML en marcas JSX.
60
60
61
61
<Note>
62
62
63
-
[JSX and React are two separate things](/blog/2020/09/22/introducing-the-new-jsx-transform.html#whats-a-jsx-transform)you _can_ use independently of each other.
63
+
[JSX y React son dos cosas separadas](/blog/2020/09/22/introducing-the-new-jsx-transform.html#whats-a-jsx-transform)que se _pueden_ usar de forma independiente.
64
64
65
65
</Note>
66
66
67
-
## Converting HTML to JSX {/*converting-html-to-jsx*/}
67
+
## Convirtiendo HTML a JSX {/*converting-html-to-jsx*/}
68
+
69
+
Supongamos que tienes algo de HTML (perfectamente válido):
68
70
69
-
Suppose that you have some (perfectly valid) HTML:
70
71
71
72
```html
72
73
<h1>Hedy Lamarr's Todos</h1>
@@ -82,7 +83,7 @@ Suppose that you have some (perfectly valid) HTML:
82
83
</ul>
83
84
```
84
85
85
-
And you want to put it into your component:
86
+
Y quieres ponerlo en tu componente:
86
87
87
88
```js
88
89
exportdefaultfunctionTodoList() {
@@ -92,7 +93,7 @@ export default function TodoList() {
92
93
}
93
94
```
94
95
95
-
If you copy and paste it as is, it will not work:
96
+
Si lo copias y pegas tal como está, no funcionará:
96
97
97
98
98
99
<Sandpack>
@@ -122,21 +123,21 @@ img { height: 90px }
122
123
123
124
</Sandpack>
124
125
125
-
This is because JSX is stricter and has a few more rules than HTML! If you read the error messages above, they'll guide you to fix the markup, or you can follow the guide below.
126
+
¡Esto se debe a que JSX es más estricto y tiene algunas restricciones más que HTML! Si lees los mensajes de error anteriores, te guiarán a corregir el marcado, o puedes seguir la guía a continuación.
126
127
127
128
<Note>
128
129
129
-
Most of the times, React's on-screen error messages will help you find where the problem is. Give them a read if you get stuck!
130
+
La mayoría de las veces, los mensajes de error en pantalla de React te ayudarán a encontrar donde está el problema. ¡Dales una lectura si te quedas atascado!.
130
131
131
132
</Note>
132
133
133
-
## The Rules of JSX {/*the-rules-of-jsx*/}
134
+
## Las Reglas de JSX {/*the-rules-of-jsx*/}
134
135
135
-
### 1. Return a single root element {/*1-return-a-single-root-element*/}
136
+
### 1. Devolver un solo elemento raíz {/*1-return-a-single-root-element*/}
136
137
137
-
To return multiple elements from a component, **wrap them with a single parent tag**.
138
+
Para devolver múltiples elementos de un componente, **envuélvelos con una sola etiqueta principal**.
138
139
139
-
For example, you can use a `<div>`:
140
+
Por ejemplo, puedes usar un `<div>`:
140
141
141
142
```js {1,11}
142
143
<div>
@@ -153,7 +154,7 @@ For example, you can use a `<div>`:
153
154
```
154
155
155
156
156
-
If you don't want to add an extra `<div>`to your markup, you can write `<>`and`</>`instead:
157
+
Si no deseas agregar un `<div>`adicional a tu marcado, puedes escribir `<>`y`</>`en su lugar:
157
158
158
159
```js {1,11}
159
160
<>
@@ -169,19 +170,19 @@ If you don't want to add an extra `<div>` to your markup, you can write `<>` and
169
170
</>
170
171
```
171
172
172
-
This empty tag is called a *[React fragment](TODO)*. React fragments let you group things without leaving any trace in the browser HTML tree.
173
+
Esta etiqueta vacía se llama *[Fragmento de React](TODO)*. Los fragmentos de React te permiten agrupar cosas sin dejar ningún rastro en el árbol HTML del navegador.
173
174
174
175
<DeepDive title="Why do multiple JSX tags need to be wrapped?">
175
176
176
-
JSX looks like HTML, but under the hood it is transformed into plain JavaScript objects. You can't return two objects from a function without wrapping them into an array. This explains why you also can't return two JSX tags without wrapping them into another tag or a fragment.
177
+
JSX parece HTML, pero por debajo se transforma en objetos planos de JavaScript. No puedes devolver dos objetos de una función sin envolverlos en un array. Esto explica por qué tampoco puedes devolver dos etiquetas JSX sin envolverlas en otra etiqueta o fragmento.
177
178
178
179
</DeepDive>
179
180
180
-
### 2. Close all the tags {/*2-close-all-the-tags*/}
181
+
### 2. Cierra todas las etiquetas {/*2-close-all-the-tags*/}
181
182
182
-
JSX requires tags to be explicitly closed: self-closing tags like `<img>` must become `<img />`, and wrapping tags like `<li>oranges` must be written as `<li>oranges</li>`.
183
+
JSX requiere que las etiquetas se cierren explícitamente: las etiquetas de cierre automático como `<img>` deben convertirse en `<img />`, y etiquetas envolventes como `<li>oranges` deben convertirse como `<li>oranges</li>`.
183
184
184
-
This is how Hedy Lamarr's image and list items look closed:
185
+
Así es como la imagen y los elementos de la lista de Hedy Lamarr se ven cerrados:
185
186
186
187
```js {2-6,8-10}
187
188
<>
@@ -198,11 +199,11 @@ This is how Hedy Lamarr's image and list items look closed:
198
199
</>
199
200
```
200
201
201
-
### 3. camelCase <s>all</s> most of the things! {/*3-camelcase-salls-most-of-the-things*/}
202
+
### 3. ¡camelCase <s>todo</s> la mayoría de las cosas! {/*3-camelcase-salls-most-of-the-things*/}
202
203
203
-
JSX turns into JavaScript and attributes written in JSX become keys of JavaScript objects. In your own components, you will often want to read those attributes into variables. But JavaScript has limitations on variable names. For example, their names can't contain dashes or be reserved words like `class`.
204
+
JSX se convierte en JavaScript y los atributos escritos en JSX se convierten en keys de objetos JavaScript. En tus propios componentes, a menudo vas a querer leer esos atributos en variables. Pero JavaScript tiene limitaciones en los nombres de variables. Por ejemplo, sus nombres no pueden contener guiones ni ser palabras reservadas como `class`.
204
205
205
-
This is why, in React, many HTML and SVG attributes are written in camelCase. For example, instead of `stroke-width` you use `strokeWidth`. Since `class` is a reserved word, in React you write `className` instead, named after the [corresponding DOM property](https://developer.mozilla.org/en-US/docs/Web/API/Element/className):
206
+
Por eso, en React, muchos atributos HTML y SVG están escritos en camelCase. Por ejemplo, en lugar de `stroke-width` usa `strokeWidth`. Dado que `class` es una palabra reservada, en React escribes `className` en su lugar, con el nombre de la [propiedad DOM correspondiente](https://developer.mozilla.org/en-US/docs/Web/API/Element/className):
206
207
207
208
```js {4}
208
209
<img
@@ -212,19 +213,19 @@ This is why, in React, many HTML and SVG attributes are written in camelCase. Fo
212
213
/>
213
214
```
214
215
215
-
Youcan [findalltheseattributesintheReactDOMElements](TODO). Ifyougetonewrong, don't worry—React will print a message with a possible correction to the [browser console](https://developer.mozilla.org/docs/Tools/Browser_Console).
216
+
Puedes [encontrar todos estos atributos en React DOM Elements](TODO). Si te equivocas en uno, no te preocupes, React imprimirá un mensaje con una posible corrección en la [consola del navegador](https://developer.mozilla.org/docs/Tools/Browser_Console).
216
217
217
218
<Gotcha>
218
219
219
-
For historical reasons, [`aria-*`](https://developer.mozilla.org/docs/Web/Accessibility/ARIA) and [`data-*`](https://developer.mozilla.org/docs/Learn/HTML/Howto/Use_data_attributes) attributes are written as in HTML with dashes.
220
+
Por razones históricas, los atributos [`aria-*`](https://developer.mozilla.org/docs/Web/Accessibility/ARIA) y [`data-*`](https://developer.mozilla.org/docs/Learn/HTML/Howto/Use_data_attributes) se escriben como en HTML, con guiones.
220
221
221
222
</Gotcha>
222
223
223
-
### Pro-tip: Use a JSX Converter {/*pro-tip-use-a-jsx-converter*/}
224
+
### Consejo profesional: usa un convertidor JSX {/*pro-tip-use-a-jsx-converter*/}
224
225
225
-
Converting all these attributes in existing markup can be tedious! We recommend using a [converter](https://transform.tools/html-to-jsx) to translate your existing HTML and SVG to JSX. Converters are very useful in practice, but it'sstillworthunderstandingwhatisgoingonsothatyoucancomfortablywriteJSXonyourown.
226
+
¡Convertir todos estos atributos en marcas existentes puede ser tedioso! Recomendamos usar un [convertidor](https://transform.tools/html-to-jsx) para traducir su HTML y SVG existente a JSX. Los convertidores son muy útiles en la práctica, pero aun así vale la pena entender lo que sucede así puedes escribir JSX cómodamente por tu cuenta.
226
227
227
-
Hereisyourfinalresult:
228
+
Aquí está tu resultado final:
228
229
229
230
<Sandpack>
230
231
@@ -256,21 +257,21 @@ img { height: 90px }
256
257
257
258
<Recap>
258
259
259
-
NowyouknowwhyJSXexistsandhowtouseitincomponents:
260
+
Ahora sabes por qué existe JSX y cómo usarlo en componentes:
0 commit comments