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
*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*é uma extensão de sintaxe para JavaScript que permite que você escreva marcação semelhante a HTML dentro de um arquivo JavaScript. Embora existam outras maneiras de escrever componentes, a maioria dos desenvolvedores React prefere a concisão de JSX, e a maioria das bases de código o utiliza.
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 que React mistura marcação com lógica de renderização
14
+
*Como JSX é diferente de HTML
15
+
*Como exibir informações com JSX
16
16
17
17
</YouWillLearn>
18
18
19
-
## JSX: Putting markup into JavaScript {/*jsx-putting-markup-into-javascript*/}
19
+
## JSX: Colocando marcação dentro do 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
+
A Web foi construída em HTML, CSS e JavaScript. Por muitos anos, os desenvolvedores web mantiveram o conteúdo em HTML, o design em CSS e a lógica em JavaScript - muitas vezes em arquivos separados! O conteúdo foi marcado dentro do HTML, enquanto a lógica da página vivia separadamente em JavaScript:
22
22
23
23
<DiagramGroup>
24
24
25
-
<Diagramname="writing_jsx_html"height={237}width={325}alt="HTML markup with purple background and a div with two child tags: p and form. ">
25
+
<Diagramname="writing_jsx_html"height={237}width={325}alt="Marcação HTML com fundo roxo e uma div com duas tags filhas: p e form. ">
26
26
27
27
HTML
28
28
29
29
</Diagram>
30
30
31
-
<Diagramname="writing_jsx_js"height={237}width={325}alt="Three JavaScript handlers with yellow background: onSubmit, onLogin, and onClick.">
31
+
<Diagramname="writing_jsx_js"height={237}width={325}alt="Três manipuladores JavaScript com fundo amarelo: onSubmit, onLogin e onClick.">
32
32
33
33
JavaScript
34
34
35
35
</Diagram>
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
+
Mas, à medida que a Web se tornou mais interativa, a lógica passou a determinar cada vez mais o conteúdo. JavaScript estava no comando do HTML! É por isso que **no React, a lógica de renderização e a marcação vivem juntas no mesmo lugar — nos componentes.**
40
40
41
41
<DiagramGroup>
42
42
43
-
<Diagramname="writing_jsx_sidebar"height={330}width={325}alt="React component with HTML and JavaScript from previous examples mixed. Function name is Sidebar which calls the function isLoggedIn, highlighted in yellow. Nested inside the function highlighted in purple is the p tag from before, and a Form tag referencing the component shown in the next diagram.">
43
+
<Diagramname="writing_jsx_sidebar"height={330}width={325}alt="Componente React com HTML e JavaScript dos exemplos anteriores misturados. O nome da função é Sidebar que chama a função isLoggedIn, destacada em amarelo. Aninhado dentro da função, destacada em roxo, está a tag p de antes, e uma tag Form referenciando o componente mostrado no diagrama seguinte.">
44
44
45
-
`Sidebar.js` React component
45
+
Componente React `Sidebar.js`
46
46
47
47
</Diagram>
48
48
49
-
<Diagramname="writing_jsx_form"height={330}width={325}alt="React component with HTML and JavaScript from previous examples mixed. Function name is Form containing two handlers onClick and onSubmit highlighted in yellow. Following the handlers is HTML highlighted in purple. The HTML contains a form element with a nested input element, each with an onClick prop.">
49
+
<Diagramname="writing_jsx_form"height={330}width={325}alt="Componente React com HTML e JavaScript dos exemplos anteriores misturados. O nome da função é Form contendo dois manipuladores onClick e onSubmit destacados em amarelo. Seguindo os manipuladores, há HTML destacado em roxo. O HTML contém um elemento form com um elemento input aninhado, cada um com uma prop onClick.">
50
50
51
-
`Form.js` React component
51
+
Componente React `Form.js`
52
52
53
53
</Diagram>
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
+
Manter a lógica de renderização e a marcação de um botão juntas garante que elas permaneçam sincronizadas entre si em cada edição. Por outro lado, os detalhes que não estão relacionados, como a marcação do botão e a marcação de uma barra lateral, são isolados uns dos outros, tornando mais seguro alterá-los separadamente.
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 React é uma função JavaScript que pode conter alguma marcação que o React renderiza no navegador. Os componentes React usam uma extensão de sintaxe chamada JSX para representar essa marcação. JSX se parece muito com HTML, mas é um pouco mais rigoroso e pode exibir informações dinâmicas. A melhor maneira de entender isso é converter alguma marcação HTML em marcação JSX.
60
60
61
61
<Note>
62
62
63
-
JSX and React are two separate things. They're often used together, but you *can*[use them independently](https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html#whats-a-jsx-transform)of each other. JSX is a syntax extension, while React is a JavaScript library.
63
+
JSX e React são duas coisas separadas. Eles são frequentemente usados juntos, mas você *pode*[usá-los independentemente](https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html#whats-a-jsx-transform)um do outro. JSX é uma extensão de sintaxe, enquanto React é uma biblioteca JavaScript.
64
64
65
65
</Note>
66
66
67
-
## Converting HTML to JSX {/*converting-html-to-jsx*/}
67
+
## Convertendo HTML para JSX {/*converting-html-to-jsx*/}
68
68
69
-
Suppose that you have some (perfectly valid) HTML:
69
+
Suponha que você tenha algum HTML (perfeitamente válido):
70
70
71
71
```html
72
-
<h1>Hedy Lamarr's Todos</h1>
72
+
<h1>Tarefas de Hedy Lamarr</h1>
73
73
<img
74
74
src="https://i.imgur.com/yXOvdOSs.jpg"
75
75
alt="Hedy Lamarr"
76
76
class="photo"
77
77
>
78
78
<ul>
79
-
<li>Invent new traffic lights
80
-
<li>Rehearse a movie scene
81
-
<li>Improve the spectrum technology
79
+
<li>Inventar novos semáforos
80
+
<li>Ensaio de uma cena de filme
81
+
<li>Melhorar a tecnologia de espectro
82
82
</ul>
83
83
```
84
84
85
-
And you want to put it into your component:
85
+
E você quer colocá-lo no seu componente:
86
86
87
87
```js
88
88
exportdefaultfunctionTodoList() {
@@ -92,25 +92,25 @@ export default function TodoList() {
92
92
}
93
93
```
94
94
95
-
If you copy and paste it as is, it will not work:
95
+
Se você copiar e colar do jeito que está, não funcionará:
96
96
97
97
98
98
<Sandpack>
99
99
100
100
```js
101
101
exportdefaultfunctionTodoList() {
102
102
return (
103
-
//This doesn't quite work!
104
-
<h1>Hedy Lamarr's Todos</h1>
103
+
//Isso não funciona direito!
104
+
<h1>Tarefas de Hedy Lamarr</h1>
105
105
<img
106
106
src="https://i.imgur.com/yXOvdOSs.jpg"
107
107
alt="Hedy Lamarr"
108
108
class="photo"
109
109
>
110
110
<ul>
111
-
<li>Invent new traffic lights
112
-
<li>Rehearse a movie scene
113
-
<li>Improve the spectrum technology
111
+
<li>Inventar novos semáforos
112
+
<li>Ensaio de uma cena de filme
113
+
<li>Melhorar a tecnologia de espectro
114
114
</ul>
115
115
);
116
116
}
@@ -122,25 +122,25 @@ img { height: 90px }
122
122
123
123
</Sandpack>
124
124
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.
125
+
Isso ocorre porque JSX é mais rigoroso e tem algumas regras a mais do que o HTML! Se você ler as mensagens de erro acima, elas o guiarão para corrigir a marcação, ou você pode seguir o guia abaixo.
126
126
127
127
<Note>
128
128
129
-
Most of the time, React's on-screen error messages will help you find where the problem is. Give them a read if you get stuck!
129
+
Na maioria das vezes, as mensagens de erro na tela do React ajudarão você a encontrar onde está o problema. Dê uma lida se você ficar preso!
130
130
131
131
</Note>
132
132
133
-
## The Rules of JSX {/*the-rules-of-jsx*/}
133
+
## As Regras do JSX {/*the-rules-of-jsx*/}
134
134
135
-
### 1. Return a single root element {/*1-return-a-single-root-element*/}
135
+
### 1. Retornar um único elemento raiz {/*1-return-a-single-root-element*/}
136
136
137
-
To return multiple elements from a component, **wrap them with a single parent tag.**
137
+
Para retornar vários elementos de um componente, **agrupe-os com uma única tag pai.**
138
138
139
-
For example, you can use a `<div>`:
139
+
Por exemplo, você pode usar um`<div>`:
140
140
141
141
```js {1,11}
142
142
<div>
143
-
<h1>Hedy Lamarr's Todos</h1>
143
+
<h1>Tarefas de Hedy Lamarr</h1>
144
144
<img
145
145
src="https://i.imgur.com/yXOvdOSs.jpg"
146
146
alt="Hedy Lamarr"
@@ -152,12 +152,11 @@ For example, you can use a `<div>`:
152
152
</div>
153
153
```
154
154
155
-
156
-
If you don't want to add an extra `<div>` to your markup, you can write `<>` and `</>` instead:
155
+
Se você não quiser adicionar um `<div>` extra à sua marcação, você pode escrever `<>` e `</>` em vez disso:
157
156
158
157
```js {1,11}
159
158
<>
160
-
<h1>Hedy Lamarr's Todos</h1>
159
+
<h1>Tarefas de Hedy Lamarr</h1>
161
160
<img
162
161
src="https://i.imgur.com/yXOvdOSs.jpg"
163
162
alt="Hedy Lamarr"
@@ -169,21 +168,21 @@ If you don't want to add an extra `<div>` to your markup, you can write `<>` and
169
168
</>
170
169
```
171
170
172
-
This empty tag is called a *[Fragment.](/reference/react/Fragment)* Fragments let you group things without leaving any trace in the browser HTML tree.
171
+
Esta tag vazia é chamada de *[Fragment.](/reference/react/Fragment)* Fragments permite que você agrupe coisas sem deixar nenhum vestígio na árvore HTML do navegador.
173
172
174
173
<DeepDive>
175
174
176
-
#### Why do multiple JSX tags need to be wrapped? {/*why-do-multiple-jsx-tags-need-to-be-wrapped*/}
175
+
#### Por que várias tags JSX precisam ser encapsuladas? {/*why-do-multiple-jsx-tags-need-to-be-wrapped*/}
177
176
178
-
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 se parece com HTML, mas por baixo ele é transformado em objetos JavaScript simples. Você não pode retornar dois objetos de uma função sem os embalar em um array. Isso explica por que também não é possível retornar duas tags JSX sem encapsulá-las em outra tag ou em um Fragment.
179
178
180
179
</DeepDive>
181
180
182
-
### 2. Close all the tags {/*2-close-all-the-tags*/}
181
+
### 2. Fechar todas as tags {/*2-close-all-the-tags*/}
183
182
184
-
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 requer que as tags sejam explicitamente fechadas: tags de fechamento automático como `<img>`devem se tornar `<img />` e tags de encapsulamento como `<li>oranges`devem ser escritas como`<li>oranges</li>`.
185
184
186
-
This is how Hedy Lamarr's image and list items look closed:
185
+
É assim que a imagem e os itens da lista de Hedy Lamarr ficam fechados:
187
186
188
187
```js {2-6,8-10}
189
188
<>
@@ -193,18 +192,18 @@ This is how Hedy Lamarr's image and list items look closed:
193
192
class="photo"
194
193
/>
195
194
<ul>
196
-
<li>Invent new traffic lights</li>
197
-
<li>Rehearse a movie scene</li>
198
-
<li>Improve the spectrum technology</li>
195
+
<li>Inventar novos semáforos</li>
196
+
<li>Ensaio de uma cena de filme</li>
197
+
<li>Melhorar a tecnologia de espectro</li>
199
198
</ul>
200
199
</>
201
200
```
202
201
203
-
### 3. camelCase <s>all</s> most of the things! {/*3-camelcase-salls-most-of-the-things*/}
202
+
### 3. camelCase <s>tudo</s> a maioria das coisas! {/*3-camelcase-salls-most-of-the-things*/}
204
203
205
-
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 transforma em JavaScript e atributos escritos em JSX se tornam chaves de objetos JavaScript. Em seus próprios componentes, você costuma querer ler esses atributos em variáveis. Mas o JavaScript tem limitações nos nomes das variáveis. Por exemplo, seus nomes não podem conter hífens ou ser palavras reservadas como`class`.
206
205
207
-
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 isso que, no React, muitos atributos HTML e SVG são escritos em camelCase. Por exemplo, em vez de `stroke-width`, você usa`strokeWidth`. Como`class`é uma palavra reservada, no React você escreve`className`em vez disso, nomeado após a [propriedade DOM correspondente](https://developer.mozilla.org/en-US/docs/Web/API/Element/className):
208
207
209
208
```js {4}
210
209
<img
@@ -214,36 +213,36 @@ This is why, in React, many HTML and SVG attributes are written in camelCase. Fo
214
213
/>
215
214
```
216
215
217
-
Youcan [findalltheseattributesinthelistofDOMcomponentprops.](/reference/react-dom/components/common) 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
+
Você pode [encontrar todos esses atributos na lista de props dos componentes DOM.](/reference/react-dom/components/common)Se você errar um, não se preocupe — o React imprimirá uma mensagem com uma possível correção no [console do navegador.](https://developer.mozilla.org/docs/Tools/Browser_Console)
218
217
219
218
<Pitfall>
220
219
221
-
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 razões históricas, os atributos [`aria-*`](https://developer.mozilla.org/docs/Web/Accessibility/ARIA)e[`data-*`](https://developer.mozilla.org/docs/Learn/HTML/Howto/Use_data_attributes)são escritos como em HTML com hífens.
222
221
223
222
</Pitfall>
224
223
225
-
### Pro-tip: Use a JSX Converter {/*pro-tip-use-a-jsx-converter*/}
224
+
### Dica profissional: Use um Conversor JSX {/*pro-tip-use-a-jsx-converter*/}
226
225
227
-
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
+
Converter todos esses atributos na marcação existente pode ser tedioso! Recomendamos usar um [conversor](https://transform.tools/html-to-jsx)para traduzir seu HTML e SVG existentes para JSX. Os conversores são muito úteis na prática, mas ainda vale a pena entender o que está acontecendo para que você possa escrever JSX confortavelmente por conta própria.
228
227
229
-
Hereisyourfinalresult:
228
+
Aqui está o seu resultado final:
230
229
231
230
<Sandpack>
232
231
233
232
```js
234
233
exportdefaultfunctionTodoList() {
235
234
return (
236
235
<>
237
-
<h1>Hedy Lamarr's Todos</h1>
236
+
<h1>Tarefas de Hedy Lamarr</h1>
238
237
<img
239
238
src="https://i.imgur.com/yXOvdOSs.jpg"
240
239
alt="Hedy Lamarr"
241
240
className="photo"
242
241
/>
243
242
<ul>
244
-
<li>Invent new traffic lights</li>
245
-
<li>Rehearse a movie scene</li>
246
-
<li>Improve the spectrum technology</li>
243
+
<li>Inventar novos semáforos</li>
244
+
<li>Ensaio de uma cena de filme</li>
245
+
<li>Melhorar a tecnologia de espectro</li>
247
246
</ul>
248
247
</>
249
248
);
@@ -258,34 +257,34 @@ img { height: 90px }
258
257
259
258
<Recap>
260
259
261
-
NowyouknowwhyJSXexistsandhowtouseitincomponents:
260
+
Agora você sabe por que JSX existe e como usá-lo em componentes:
0 commit comments