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: src/content/learn/javascript-in-jsx-with-curly-braces.md
+56-56
Original file line number
Diff line number
Diff line change
@@ -1,25 +1,25 @@
1
1
---
2
-
title: JavaScript in JSX with Curly Braces
2
+
title: JavaScript em JSX com chaves
3
3
---
4
4
5
5
<Intro>
6
6
7
-
JSX lets you write HTML-like markup inside a JavaScript file, keeping rendering logic and content in the same place. Sometimes you will want to add a little JavaScript logic or reference a dynamic property inside that markup. In this situation, you can use curly braces in your JSX to open a window to JavaScript.
7
+
A sintaxe JSX permite que você escreva tags similares ao HTML dentro de um arquivo JavaScript, mantendo a lógica de renderização e o conteúdo no mesmo local. Às vezes, você pode querer adicionar um pouco de lógica JavaScript ou referenciar uma propriedade dinâmica dentro deste bloco de tags. Nessa situação, você pode usar chaves em seu JSX para abrir uma janela para o JavaScript.
8
8
9
9
</Intro>
10
10
11
11
<YouWillLearn>
12
12
13
-
*How to pass strings with quotes
14
-
*How to reference a JavaScript variable inside JSX with curly braces
15
-
*How to call a JavaScript function inside JSX with curly braces
16
-
*How to use a JavaScript object inside JSX with curly braces
13
+
*Como passar strings com aspas
14
+
*Como fazer referência a uma variável JavaScript dentro do JSX usando chaves
15
+
*Como chamar uma função JavaScript dentro da JSX com chaves
16
+
*Como usar um objeto JavaScript dentro da JSX com chaves
17
17
18
18
</YouWillLearn>
19
19
20
-
## Passing strings with quotes {/*passing-strings-with-quotes*/}
20
+
## Passando strings com aspas {/*passing-strings-with-quotes*/}
21
21
22
-
When you want to pass a string attribute to JSX, you put it in single or double quotes:
22
+
Quando você quiser passar um atributo de string para a JSX, coloque-o entre aspas simples ou duplas:
23
23
24
24
<Sandpack>
25
25
@@ -41,9 +41,9 @@ export default function Avatar() {
41
41
42
42
</Sandpack>
43
43
44
-
Here, `"https://i.imgur.com/7vQD0fPs.jpg"`and`"Gregorio Y. Zara"`are being passed as strings.
44
+
Neste caso, `"https://i.imgur.com/7vQD0fPs.jpg"`e`"Gregorio Y. Zara"`estão sendo passados como strings.
45
45
46
-
But what if you want to dynamically specify the`src`or`alt` text? You could**use a value from JavaScript by replacing `"`and`"`with`{`and`}`**:
46
+
Mas e se você quiser especificar dinamicamente o atributo`src`ou`alt`? Você poderia**usar um valor do JavaScript substituindo `"`e`"`por`{`e`}`**:
47
47
48
48
<Sandpack>
49
49
@@ -67,11 +67,11 @@ export default function Avatar() {
67
67
68
68
</Sandpack>
69
69
70
-
Notice the difference between`className="avatar"`, which specifies an `"avatar"`CSS class name that makes the image round, and`src={avatar}` that reads the value of the JavaScript variable called `avatar`. That's because curly braces let you work with JavaScript right there in your markup!
70
+
Perceba a diferença entre`className="avatar"`, que especifica um nome de classe CSS `"avatar"`para tornar a imagem redonda, e`src={avatar}`, que lê o valor da variável JavaScript chamada `avatar`. Isso ocorre porque as chaves permitem que você trabalhe com JavaScript diretamente em seu bloco de tags!
71
71
72
-
## Using curly braces: A window into the JavaScript world {/*using-curly-braces-a-window-into-the-javascript-world*/}
72
+
## Usando chaves: Uma janela para o mundo do JavaScript {/*using-curly-braces-a-window-into-the-javascript-world*/}
73
73
74
-
JSX is a special way of writing JavaScript. That means it’s possible to use JavaScript inside it—with curly braces `{ }`. The example below first declares a name for the scientist, `name`, then embeds it with curly braces inside the `<h1>`:
74
+
JSX é uma forma especial de escrever JavaScript. Isso significa que é possível usar JavaScript dentro dela - com chaves `{ }`. O exemplo abaixo primeiro declara um nome para o cientista, `name`, e depois o insere o dentro do `<h1>` com chaves:
75
75
76
76
<Sandpack>
77
77
@@ -86,9 +86,9 @@ export default function TodoList() {
86
86
87
87
</Sandpack>
88
88
89
-
Try changing the `name`'s value from `'Gregorio Y. Zara'`to`'Hedy Lamarr'`. See how the list title changes?
89
+
Tente trocar o valor do `name` de `'Gregorio Y. Zara'` para `'Hedy Lamarr'`. Está vendo como o título da lista muda?
90
90
91
-
Any JavaScript expression will work between curly braces, including function calls like `formatDate()`:
91
+
Qualquer expressão JavaScript funcionará entre chaves, incluindo chamadas de função como `formatDate()`:
92
92
93
93
<Sandpack>
94
94
@@ -111,18 +111,18 @@ export default function TodoList() {
111
111
112
112
</Sandpack>
113
113
114
-
### Where to use curly braces {/*where-to-use-curly-braces*/}
114
+
### Onde usar chaves {/*where-to-use-curly-braces*/}
115
115
116
-
You can only use curly braces in two ways inside JSX:
116
+
Você só pode usar chaves de duas maneiras dentro da JSX:
117
117
118
-
1. **As text** directly inside a JSX tag: `<h1>{name}'s To Do List</h1>` works, but `<{tag}>Gregorio Y. Zara's To Do List</{tag}>` will not.
119
-
2. **As attributes** immediately following the `=` sign: `src={avatar}`will read the`avatar` variable, but`src="{avatar}"`will pass the string `"{avatar}"`.
118
+
1. **Como texto** diretamente dentro de uma tag JSX: `<h1>{nome}'s To Do List</h1>`funciona, porém`<{tag}>Gregorio Y. Zara's To Do List</{tag}>` não funcionará.
119
+
2. **Como atributos** imediatamente após o sinal `=`: `src={avatar}` lerá a variável `avatar`, mas `src="{avatar}"` passará a string `"{avatar}"`.
120
120
121
-
## Using "double curlies": CSS and other objects in JSX {/*using-double-curlies-css-and-other-objects-in-jsx*/}
121
+
## Uso de "chaves duplas": CSS e outros objetos em JSX {/*using-double-curlies-css-and-other-objects-in-jsx*/}
122
122
123
-
In addition to strings, numbers, and other JavaScript expressions, you can even pass objects in JSX. Objects are also denoted with curly braces, like`{ name:"Hedy Lamarr", inventions:5 }`. Therefore, to pass a JS object in JSX, you must wrap the object in another pair of curly braces: `person={{ name:"Hedy Lamarr", inventions:5 }}`.
123
+
Além de strings, números e outras expressões JavaScript, você pode até passar objetos em JSX. Os objetos também são denotados por chaves, como `{ name: "Hedy Lamarr", inventions: 5 }`. Portanto, para passar um objeto JS em JSX, você deve envolver o objeto em outro par de chaves: `person={{ name: "Hedy Lamarr", inventions: 5 }}`.
124
124
125
-
You may see this with inline CSS styles in JSX. React does not require you to use inline styles (CSS classes work great for most cases). But when you need an inline style, you pass an object to the `style` attribute:
125
+
Você pode ver isso com estilos CSS em linha na JSX. O React não exige que você use estilos inline (as classes CSS funcionam muito bem na maioria dos casos). Mas quando você precisa de um estilo inline, você passa um objeto para o atributo `style`:
126
126
127
127
<Sandpack>
128
128
@@ -148,9 +148,9 @@ ul { padding: 20px 20px 20px 40px; margin: 0; }
148
148
149
149
</Sandpack>
150
150
151
-
Try changing the values of`backgroundColor`and`color`.
151
+
Tente alterar os valores de `backgroundColor` e `color`.
152
152
153
-
You can really see the JavaScript object inside the curly braces when you write it like this:
153
+
Você pode ver claramente o objeto JavaScript dentro das chaves quando o escreve dessa forma:
154
154
155
155
```js {2-5}
156
156
<ul style={
@@ -161,17 +161,17 @@ You can really see the JavaScript object inside the curly braces when you write
161
161
}>
162
162
```
163
163
164
-
The next time you see `{{`and`}}`in JSX, know that it's nothing more than an object inside the JSX curlies!
164
+
Da próxima vez que você encontrar `{{` e `}}` em JSX, saiba que isso é nada mais do que um objeto dentro das chaves da JSX!
165
165
166
166
<Pitfall>
167
167
168
-
Inline `style`properties are written in camelCase. For example, HTML `<ul style="background-color: black"`> would be written as `<ul style={{ backgroundColor:'black' }}>` in your component.
168
+
As propriedades de `style` em linha são escritas em camelCase. Por exemplo, o HTML `<ul style="background-color: black"`> seria escrito como `<ul style={{ backgroundColor: 'black' }}>` em seu componente.
169
169
170
170
</Pitfall>
171
171
172
-
## More fun with JavaScript objects and curly braces {/*more-fun-with-javascript-objects-and-curly-braces*/}
172
+
## Mais diversão com objetos JavaScript e chaves {/*more-fun-with-javascript-objects-and-curly-braces*/}
173
173
174
-
You can move several expressions into one object, and reference them in your JSX inside curly braces:
174
+
Você pode colocar várias expressões dentro de um objeto e referenciá-las em seu JSX dentro de chaves:
175
175
176
176
<Sandpack>
177
177
@@ -211,7 +211,7 @@ body > div > div { padding: 20px; }
211
211
212
212
</Sandpack>
213
213
214
-
In this example, the `person` JavaScript object contains a `name` string and a `theme` object:
214
+
Neste exemplo, o objeto JavaScript `person`contém uma string `name`e um objeto`theme`:
215
215
216
216
```js
217
217
constperson= {
@@ -223,31 +223,31 @@ const person = {
223
223
};
224
224
```
225
225
226
-
The component can use these values from `person` like so:
226
+
O componente pode usar os valores de`person`da seguinte forma:
227
227
228
228
```js
229
229
<div style={person.theme}>
230
230
<h1>{person.name}'s Todos</h1>
231
231
```
232
232
233
-
JSX is very minimal as a templating language because it lets you organize data and logic using JavaScript.
233
+
JSX é uma linguagem de modelação mínima, pois permite que você organize dados e lógica usando JavaScript.
234
234
235
235
<Recap>
236
236
237
-
Now you know almost everything about JSX:
237
+
Agora você sabe quase tudo sobre JSX:
238
238
239
-
* JSX attributes inside quotes are passed as strings.
240
-
* Curly braces let you bring JavaScript logic and variables into your markup.
241
-
* They work inside the JSX tag content or immediately after`=`in attributes.
242
-
* `{{`and`}}`is not special syntax: it's a JavaScript object tucked inside JSX curly braces.
239
+
* Os atributos JSX entre aspas são passados como strings.
240
+
* As chaves permitem que você inclua a lógica e as variáveis do JavaScript em seu bloco de tags.
241
+
* Elas funcionam dentro do conteúdo da tag JSX ou imediatamente após `=` em atributos.
242
+
* `{{` e `}}` não é uma sintaxe especial: é um objeto JavaScript colocado entre chaves JSX.
243
243
244
244
</Recap>
245
245
246
246
<Challenges>
247
247
248
-
#### Fix the mistake {/*fix-the-mistake*/}
248
+
#### Corrija o erro {/*fix-the-mistake*/}
249
249
250
-
This code crashes with an error saying `Objects are not valid as a React child`:
250
+
Este código é interrompido com um erro dizendo `Objetos não são válidos como um filho React`:
251
251
252
252
<Sandpack>
253
253
@@ -287,15 +287,15 @@ body > div > div { padding: 20px; }
287
287
288
288
</Sandpack>
289
289
290
-
Can you find the problem?
290
+
Você consegue identificar o problema?
291
291
292
-
<Hint>Look for what's inside the curly braces. Are we putting the right thing there?</Hint>
292
+
<Hint>Observe o que está dentro das chaves. Estamos colocando a coisa certa lá?</Hint>
293
293
294
294
<Solution>
295
295
296
-
This is happening because this example renders *an object itself* into the markup rather than a string:`<h1>{person}'s Todos</h1>`is trying to render the entire `person`object! Including raw objects as text content throws an error because React doesn't know how you want to display them.
296
+
Isso está acontecendo porque esse exemplo renderiza *um objeto* no bloco de tags em vez de uma string: `<h1>{person}'s Todos</h1>`está tentando renderizar o objeto `person`inteiro! A inclusão de objetos diretamente como conteúdo de texto gera um erro porque o React não sabe como você deseja exibi-los.
297
297
298
-
To fix it, replace `<h1>{person}'s Todos</h1>`with`<h1>{person.name}'s Todos</h1>`:
298
+
Para corrigi-lo, substitua`<h1>{person}'s Todos</h1>`por`<h1>{person.name}'s Todos</h1>`:
299
299
300
300
<Sandpack>
301
301
@@ -337,9 +337,9 @@ body > div > div { padding: 20px; }
337
337
338
338
</Solution>
339
339
340
-
#### Extract information into an object {/*extract-information-into-an-object*/}
340
+
#### Extraia informações para um objeto {/*extract-information-into-an-object*/}
341
341
342
-
Extract the image URL into the `person` object.
342
+
Extraia o URL da imagem para o objeto `person`.
343
343
344
344
<Sandpack>
345
345
@@ -381,7 +381,7 @@ body > div > div { padding: 20px; }
381
381
382
382
<Solution>
383
383
384
-
Move the image URL into a property called `person.imageUrl` and read it from the `<img>` tag using the curlies:
384
+
Mova o URL da imagem para uma propriedade chamada `person.imageUrl`e leia-o a partir da tag `<img>`usando chaves:
385
385
386
386
<Sandpack>
387
387
@@ -424,13 +424,13 @@ body > div > div { padding: 20px; }
424
424
425
425
</Solution>
426
426
427
-
#### Write an expression inside JSX curly braces {/*write-an-expression-inside-jsx-curly-braces*/}
427
+
#### Escreva uma expressão entre chaves JSX {/*write-an-expression-inside-jsx-curly-braces*/}
428
428
429
-
In the object below, the full image URL is split into four parts: base URL, `imageId`, `imageSize`, and file extension.
429
+
No objeto abaixo, o URL completo da imagem é dividido em quatro partes: URL base, `imageId`, `imageSize` e extensão do arquivo.
430
430
431
-
We want the image URL to combine these attributes together: base URL (always`'https://i.imgur.com/'`), `imageId` (`'7vQD0fP'`), `imageSize` (`'s'`), and file extension (always`'.jpg'`). However, something is wrong with how the `<img>`tag specifies its`src`.
431
+
Queremos que o URL da imagem combine estes atributos: URL base (sempre `'https://i.imgur.com/'`), `imageId` (`'7vQD0fP'`), `imageSize` (`'s'`) e extensão de arquivo (sempre `'.jpg'`). Entretanto, há algo errado com a forma como a tag `<img>` especifica sua `src`.
432
432
433
-
Can you fix it?
433
+
Você pode consertá-lo?
434
434
435
435
<Sandpack>
436
436
@@ -474,15 +474,15 @@ body > div > div { padding: 20px; }
474
474
475
475
</Sandpack>
476
476
477
-
To check that your fix worked, try changing the value of `imageSize` to `'b'`. The image should resize after your edit.
477
+
Para verificar se sua correção funcionou, tente alterar o valor de`imageSize`para`'b'`. A imagem deverá ser redimensionada após sua edição.
478
478
479
479
<Solution>
480
480
481
-
You can write it as `src={baseUrl + person.imageId + person.imageSize + '.jpg'}`.
481
+
Você pode escrevê-lo como`src={baseUrl + person.imageId + person.imageSize + '.jpg'}`.
0 commit comments