diff --git a/src/content/learn/tutorial-tic-tac-toe.md b/src/content/learn/tutorial-tic-tac-toe.md index 28d997b04..a94471e6c 100644 --- a/src/content/learn/tutorial-tic-tac-toe.md +++ b/src/content/learn/tutorial-tic-tac-toe.md @@ -1,31 +1,31 @@ --- -title: 'Tutorial: Tic-Tac-Toe' +title: 'Tutorial: Jogo da Velha' --- -You will build a small tic-tac-toe game during this tutorial. This tutorial does not assume any existing React knowledge. The techniques you'll learn in the tutorial are fundamental to building any React app, and fully understanding it will give you a deep understanding of React. +Você construirá um pequeno jogo da velha durante este tutorial. Este tutorial não assume qualquer conhecimento prévio em React. As técnicas que você aprenderá no tutorial são fundamentais à construção de qualquer aplicativo React, e o entendimento destas lhe dará conhecimentos aprofundados sobre o React. -This tutorial is designed for people who prefer to **learn by doing** and want to quickly try making something tangible. If you prefer learning each concept step by step, start with [Describing the UI.](/learn/describing-the-ui) +Este tutorial foi criado para pessoas as quais preferem **aprender na prática** e querem tentar fazer algo tangível rapidamente. Se você prefere aprender cada conceito passo a passo, comece por [Descrevendo a UI.](/learn/describing-the-ui) -The tutorial is divided into several sections: +O tutorial é dividido em diversas seções: -- [Setup for the tutorial](#setup-for-the-tutorial) will give you **a starting point** to follow the tutorial. -- [Overview](#overview) will teach you **the fundamentals** of React: components, props, and state. -- [Completing the game](#completing-the-game) will teach you **the most common techniques** in React development. -- [Adding time travel](#adding-time-travel) will give you **a deeper insight** into the unique strengths of React. +- [Preparação para o tutorial](#setup-for-the-tutorial) dará **um ponto de partida** para seguir o tutorial. +- [Visão geral](#overview) ensinará os **fundamentos** do React: componentes, *props*, e *state*. +- [Completando o jogo](#completing-the-game) ensinará a você **as técnicas mais comuns** no desenvolvimento React. +- [Adicionando viagem no tempo](#adding-time-travel) dará **uma visão aprofundada** sobre os pontos fortes únicos do React. -### What are you building? {/*what-are-you-building*/} +### O quê você está construindo? {/*what-are-you-building*/} -In this tutorial, you'll build an interactive tic-tac-toe game with React. +Neste tutorial, você construirá um jogo interativo de jogo da velha com React. -You can see what it will look like when you're finished here: +Você pode ver com o que ele se parecerá quando você tiver terminado aqui: @@ -194,15 +194,15 @@ body { -If the code doesn't make sense to you yet, or if you are unfamiliar with the code's syntax, don't worry! The goal of this tutorial is to help you understand React and its syntax. +Se o código não faz sentido para você ainda, ou se você não tem familiaridade com a sintaxe do código, não se preocupe! O objetivo deste tutorial é ajudá-lo a entender o React e a sua sintaxe. -We recommend that you check out the tic-tac-toe game above before continuing with the tutorial. One of the features that you'll notice is that there is a numbered list to the right of the game's board. This list gives you a history of all of the moves that have occurred in the game, and it is updated as the game progresses. +Nós recomendamos que você cheque o jogo da velha acima antes de continuar com o tutorial. Uma das funções que você perceberá é a de que existe uma lista numerada à direita do tabuleiro do jogo. Essa lista fornece um histórico de todos os movimentos que ocorreram no jogo, e é atualizada conforme o jogo progride. -Once you've played around with the finished tic-tac-toe game, keep scrolling. You'll start with a simpler template in this tutorial. Our next step is to set you up so that you can start building the game. +Uma vez que você tenha brincado com o jogo da velha finalizado, continue rolando a página. Você iniciará com um modelo mais simples neste tutorial. Nosso próximo passo é prepará-lo para que você possa começar a construir o jogo. -## Setup for the tutorial {/*setup-for-the-tutorial*/} +## Preparação para o tutorial {/*setup-for-the-tutorial*/} -In the live code editor below, click **Fork** in the top-right corner to open the editor in a new tab using the website CodeSandbox. CodeSandbox lets you write code in your browser and preview how your users will see the app you've created. The new tab should display an empty square and the starter code for this tutorial. +No editor de código abaixo, clique em **Fork** no canto superior direito para abri-lo em uma nova aba usando o site CodeSandbox. O CodeSandbox permite que você escreva código em seu navegador e pré-visualize como os seus usuários verão o aplicativo que você criou. A nova aba deve exibir um quadrado vazio e o código inicial para este tutorial. @@ -261,33 +261,33 @@ body { -You can also follow this tutorial using your local development environment. To do this, you need to: +Você também pode seguir esse tutorial usando o seu ambiente de desenvolvimento local. Para fazer isso, você precisará: -1. Install [Node.js](https://nodejs.org/en/) -1. In the CodeSandbox tab you opened earlier, press the top-left corner button to open the menu, and then choose **File > Export to ZIP** in that menu to download an archive of the files locally -1. Unzip the archive, then open a terminal and `cd` to the directory you unzipped -1. Install the dependencies with `npm install` -1. Run `npm start` to start a local server and follow the prompts to view the code running in a browser +1. Instalar [Node.js](https://nodejs.org/en/) +1. Na aba do CodeSandbox que você abriu anteriormente, pressione o botão no canto superior esquerdo para abrir o menu e então escolha **Arquivo > Exportar como ZIP** naquele menu para baixar os arquivos localmente +1. Descompacte o arquivo, então abra um terminal e execute `cd` até o diretório em que você os descompactou +1. Instale as dependências com `npm install` +1. Execute `npm start` para iniciar um servidor local e siga os prompts para ver o código rodando em um navegador -If you get stuck, don't let this stop you! Follow along online instead and try a local setup again later. +Se você tiver problemas, não deixe com que isso lhe pare! Ao invés disso continue online e tente novamente em ambiente local mais tarde. -## Overview {/*overview*/} +## Visão geral {/*overview*/} -Now that you're set up, let's get an overview of React! +Agora que você está preparado, vamos ter uma visão geral to React! -### Inspecting the starter code {/*inspecting-the-starter-code*/} +### Inspecionando o código inicial {/*inspecting-the-starter-code*/} -In CodeSandbox you'll see three main sections: +No CodeSandbox você verá três seções principais: -![CodeSandbox with starter code](../images/tutorial/react-starter-code-codesandbox.png) +![CodeSandbox com código inicial](../images/tutorial/react-starter-code-codesandbox.png) -1. The _Files_ section with a list of files like `App.js`, `index.js`, `styles.css` and a folder called `public` -1. The _code editor_ where you'll see the source code of your selected file -1. The _browser_ section where you'll see how the code you've written will be displayed +1. A seção *Arquivos* com uma lista de arquivos como `App.js`, `index.js`, `styles.css` e uma pasta chamada `public` +1. O *editor de código* onde você verá o código fonte de seu arquivo selecionado +1. A seção de *navegador* onde você verá como o código que você escreveu será exibido -The `App.js` file should be selected in the _Files_ section. The contents of that file in the _code editor_ should be: +O arquivo `App.js` deve ser selecionado na seção *Arquivos*. Os conteúdos daquele arquivo no *editor de código* devem ser: ```jsx export default function Square() { @@ -295,15 +295,15 @@ export default function Square() { } ``` -The _browser_ section should be displaying a square with a X in it like this: +A seção *navegador* deve estar exibindo um quadrado com um X em seu interior desta forma: -![x-filled square](../images/tutorial/x-filled-square.png) +![quadrado preenchido por um x](../images/tutorial/x-filled-square.png) -Now let's have a look at the files in the starter code. +Agora vamos dar uma olhada nos arquivos do código inicial. #### `App.js` {/*appjs*/} -The code in `App.js` creates a _component_. In React, a component is a piece of reusable code that represents a part of a user interface. Components are used to render, manage, and update the UI elements in your application. Let's look at the component line by line to see what's going on: +O código em `App.js` cria um *componente*. No React, um componente é uma peça de código reutilizável a qual representa uma parte de sua interface de usuário. Componentes são usados para renderizar, administrar, e atualizar os elementos de UI na sua aplicação. Vamos ler o componente linha a linha para entender o que está acontecendo: ```js {1} export default function Square() { @@ -311,7 +311,7 @@ export default function Square() { } ``` -The first line defines a function called `Square`. The `export` JavaScript keyword makes this function accessible outside of this file. The `default` keyword tells other files using your code that it's the main function in your file. +A primeira linha define uma função chamada `Square`. A palavra-chave do JavaScript `export` torna essa função acessível fora deste arquivo. O termo `default` diz aos outros arquivos usando seu código que essa é a função principal em seu arquivo. ```js {2} export default function Square() { @@ -319,15 +319,15 @@ export default function Square() { } ``` -The second line returns a button. The `return` JavaScript keyword means whatever comes after is returned as a value to the caller of the function. `` closes the JSX element to indicate that any following content shouldn't be placed inside the button. +A segunda linha retorna um botão. A palavra-chave `return` do JavaScript significa que qualquer coisa que venha após ela é retornada como um valor para quem chamar esta função. `` fecha o elemento JSX para indicar que qualquer conteúdo após isso não deve ser colocado dentro do botão. #### `styles.css` {/*stylescss*/} -Click on the file labeled `styles.css` in the _Files_ section of CodeSandbox. This file defines the styles for your React app. The first two _CSS selectors_ (`*` and `body`) define the style of large parts of your app while the `.square` selector defines the style of any component where the `className` property is set to `square`. In your code, that would match the button from your Square component in the `App.js` file. +Clique no arquivo denominado `styles.css` na seção *Arquivos* do CodeSandbox. Esse arquivo define os estilos para a sua aplicação React. Os primeiros dois *seletores CSS* (`*` e `body`) definem o estilo de grandes parte do seu aplicativo enquanto o seletor `.square` define o estilo de qualquer componente onde a propriedade `className` esteja definida como `square`. Em seu código, isso se refere ao botão de seu componente Square no arquivo `App.js`. #### `index.js` {/*indexjs*/} -Click on the file labeled `index.js` in the _Files_ section of CodeSandbox. You won't be editing this file during the tutorial but it is the bridge between the component you created in the `App.js` file and the web browser. +Clique no arquivo denominado `index.js` na seção *Arquivos* de seu CodeSandbox. Você não editará este arquivo durante o tutorial mas ele é a ponte entre o componente que você criou no arquivo `App.js` e o navegador. ```jsx import { StrictMode } from 'react'; @@ -337,20 +337,20 @@ import './styles.css'; import App from './App'; ``` -Lines 1-5 brings all the necessary pieces together: +As linhas 1-5 juntam todas as peças necessárias: -* React -* React's library to talk to web browsers (React DOM) -* the styles for your components -* the component you created in `App.js`. +- React +- a biblioteca do React para conversar com navegadores de internet (React DOM) +- os estilos de seus componentes +- o componente que você criou em `App.js`. -The remainder of the file brings all the pieces together and injects the final product into `index.html` in the `public` folder. +O restante do arquivo junta todas as partes e injeta o produto final em `index.html` na pasta `public`. -### Building the board {/*building-the-board*/} +### Construindo o tabuleiro {/*building-the-board*/} -Let's get back to `App.js`. This is where you'll spend the rest of the tutorial. +Vamos voltar ao `App.js`. É aqui que você passará o restante do tutorial. -Currently the board is only a single square, but you need nine! If you just try and copy paste your square to make two squares like this: +Atualmente o tabuleiro é apenas um único quadrado, mas você precisa de nove! Se você simplesmente tentar copiar e colar seu quadrado para fazer dois quadrados desta forma: ```js {2} export default function Square() { @@ -358,15 +358,15 @@ export default function Square() { } ``` -You'll get this error: +Você receberá este erro: -/src/App.js: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment `<>...`? +/src/App.js: Elementos JSX adjacentes devem ser envolvidos em uma tag externa. Você queria um fragment JSX `<>...`? -React components need to return a single JSX element and not multiple adjacent JSX elements like two buttons. To fix this you can use *fragments* (`<>` and ``) to wrap multiple adjacent JSX elements like this: +Componentes do React precisam retornar um único elemento JSX e não múltiplos elementos JSX adjacentes como dois botões. Para consertar isso você pode usar *fragments* (`<>` e ``) para envolver múltiplos elementos JSX adjacentes desta forma: ```js {3-6} export default function Square() { @@ -379,17 +379,17 @@ export default function Square() { } ``` -Now you should see: +Agora você deve ver: -![two x-filled squares](../images/tutorial/two-x-filled-squares.png) +![dois quadrados preenchidos por x](../images/tutorial/two-x-filled-squares.png) -Great! Now you just need to copy-paste a few times to add nine squares and... +Ótimo! Agora você só precisa copiar e colar algumas vezes para adicionar nove quadrados e... -![nine x-filled squares in a line](../images/tutorial/nine-x-filled-squares.png) +![nove quadrados preenchidos por x em uma linha](../images/tutorial/nine-x-filled-squares.png) -Oh no! The squares are all in a single line, not in a grid like you need for our board. To fix this you'll need to group your squares into rows with `div`s and add some CSS classes. While you're at it, you'll give each square a number to make sure you know where each square is displayed. +Ah não! Os quadrados estão todos em uma única linha, não em uma grade como você precisa para nosso tabuleiro. Para consertar isso, você precisará agrupar seus quadrados em linhas com `div`s e adicionar algumas classes CSS. Enquanto você o faz, dê a cada quadrado um número para certificar-se de que você sabe onde cada quadrado está sendo exibido. -In the `App.js` file, update the `Square` component to look like this: +No arquivo `App.js`, atualize o componente `Square` para que se pareça com isto: ```js {3-19} export default function Square() { @@ -415,11 +415,11 @@ export default function Square() { } ``` -The CSS defined in `styles.css` styles the divs with the `className` of `board-row`. Now that you've grouped your components into rows with the styled `div`s you have your tic-tac-toe board: +A CSS definida em `styles.css` estiliza as divs com o `className` de `board-row`. Agora que você agrupou os seus componentes em linhas com as `div`s estilizadas você tem seu tabuleiro de jogo da velha: -![tic-tac-toe board filled with numbers 1 through 9](../images/tutorial/number-filled-board.png) +![tabuleiro de jogo da velha preenchido com os números de 1 a 9](../images/tutorial/number-filled-board.png) -But you now have a problem. Your component named `Square`, really isn't a square anymore. Let's fix that by changing the name to `Board`: +Mas agora você tem um problema. Seu componente chamado `Square`, na verdade não é mais um quadrado. Vamos arrumar isso trocando o nome para `Board`: ```js {1} export default function Board() { @@ -427,7 +427,7 @@ export default function Board() { } ``` -At this point your code should look something like this: +A esse ponto seu código deve se parecer com isto: @@ -504,15 +504,15 @@ body { -Psssst... That's a lot to type! It's okay to copy and paste code from this page. However, if you're up for a little challenge, we recommend only copying code that you've manually typed at least once yourself. +Pssss... Isso é bastante para se digitar! É OK copiar e colar código desta página. Entretanto, se você está disposto a topar um desafio, nós recomendamos apenas copiar código que você mesmo já escreveu manualmente antes. -### Passing data through props {/*passing-data-through-props*/} +### Passando dados através de *props* {/*passing-data-through-props*/} -Next, you'll want to change the value of a square from empty to "X" when the user clicks on the square. With how you've built the board so far you would need to copy-paste the code that updates the square nine times (once for each square you have)! Instead of copy-pasting, React's component architecture allows you to create a reusable component to avoid messy, duplicated code. +Após isso, você gostará de mudar o valor de um quadrado de vazio para "X" quando o usuário clicar no quadrado. Com a maneira em que você construiu o tabuleiro até agora você teria que copiar e colar o código que atualiza o quadrado nove vezes (uma para cada quadrado que você tem)! Ao invés de copiar e colar, a arquitetura de componentes do React permite que você crie um componente reutilizável para evitar código bagunçado e duplicado. -First, you are going to copy the line defining your first square (``) from your `Board` component into a new `Square` component: +Primeiro, você irá copiar a linha definindo o seu primeiro quadrado (``) de seu componente `Board` a um novo componente `Square`: ```js {1-3} function Square() { @@ -524,7 +524,7 @@ export default function Board() { } ``` -Then you'll update the Board component to render that `Square` component using JSX syntax: +Então você atualizará o componente do tabuleiro para renderizar aquele componente `Square` usando a sintaxe JSX: ```js {5-19} // ... @@ -551,15 +551,15 @@ export default function Board() { } ``` -Note how unlike the browser `div`s, your own components `Board` and `Square` must start with a capital letter. +Perceba como diferentes das `div`s do navegador, os componentes `Board` e `Square` pertencem a você e devem começar com uma letra maiúscula. -Let's take a look: +Vamos dar uma olhada: -![one-filled board](../images/tutorial/board-filled-with-ones.png) +![tabuleiro preenchido pela número 1](../images/tutorial/board-filled-with-ones.png) -Oh no! You lost the numbered squares you had before. Now each square says "1". To fix this, you will use *props* to pass the value each square should have from the parent component (`Board`) to its child (`Square`). +Ah não! Você perdeu os quadrados numerados que tinha antes. Agora cada quadrado diz "1". Para consertar isso, você usará *props* para passar o valor que cada quadrado deve ter a partir de seu componente pai (`Board`) para seus filhos (`Square`). -Update the `Square` component to read the `value` prop that you'll pass from the `Board`: +Atualize o componente `Square` para ler a *prop* `value` que você irá passar a partir de `Board`: ```js {1} function Square({ value }) { @@ -567,9 +567,9 @@ function Square({ value }) { } ``` -`function Square({ value })` indicates the Square component can be passed a prop called `value`. +`function Square({ value })` indica que o componente Square aceita receber uma *prop* chamada `value`. -Now you want to display that `value` instead of `1` inside every square. Try doing it like this: +Agora você quer exibir aquele `value` ao invés de `1` dentro de cada quadrado. Tente fazer isso desta forma: ```js {2} function Square({ value }) { @@ -577,11 +577,11 @@ function Square({ value }) { } ``` -Oops, this is not what you wanted: +Ops, isto não é o que você queria: -![value-filled board](../images/tutorial/board-filled-with-value.png) +![tabuleiro preenchido com "value"](../images/tutorial/board-filled-with-value.png) -You wanted to render the JavaScript variable called `value` from your component, not the word "value". To "escape into JavaScript" from JSX, you need curly braces. Add curly braces around `value` in JSX like so: +Você queria renderizar a variável JavaScript chamada `value` a partir de seu componente, não a palavra "value". Para "escapar ao JavaScript" a partir da JSX, você precisa de chaves. Adicione chaves ao redor de `value` na JSX desta forma: ```js {2} function Square({ value }) { @@ -589,11 +589,11 @@ function Square({ value }) { } ``` -For now, you should see an empty board: +Por enquanto, você deve ver um tabuleiro vazio: -![empty board](../images/tutorial/empty-board.png) +![tabuleiro vazio](../images/tutorial/empty-board.png) -This is because the `Board` component hasn't passed the `value` prop to each `Square` component it renders yet. To fix it you'll add the `value` prop to each `Square` component rendered by the `Board` component: +Isso é porque o componente `Board` não passou a *prop* `value` a cada componente `Square` que ele renderiza ainda. Para consertar isso você adicionará a *prop* `value` a cada componente `Square` renderizado pelo componente `Board`: ```js {5-7,10-12,15-17} export default function Board() { @@ -619,11 +619,11 @@ export default function Board() { } ``` -Now you should see a grid of numbers again: +Agora você deve ver uma grade de números novamente: -![tic-tac-toe board filled with numbers 1 through 9](../images/tutorial/number-filled-board.png) +![tabuleiro de jogo da velha preenchido com números de 1 a 9](../images/tutorial/number-filled-board.png) -Your updated code should look like this: +O seu código atualizado deve se parecer com isto: @@ -702,9 +702,9 @@ body { -### Making an interactive component {/*making-an-interactive-component*/} +### Fazendo um componente interativo {/*making-an-interactive-component*/} -Let's fill the `Square` component with an `X` when you click it. Declare a function called `handleClick` inside of the `Square`. Then, add `onClick` to the props of the button JSX element returned from the `Square`: +Vamos preencher o componente `Square` com um `X` quando você o clicar. Declare uma função chamada `handleClick` dentro de `Square`. Então, adicione `onClick` às *props* do elemento JSX `button` retornado de `Square`: ```js {2-4,9} function Square({ value }) { @@ -723,19 +723,19 @@ function Square({ value }) { } ``` -If you click on a square now, you should see a log saying `"clicked!"` in the _Console_ tab at the bottom of the _Browser_ section in CodeSandbox. Clicking the square more than once will log `"clicked!"` again. Repeated console logs with the same message will not create more lines in the console. Instead, you will see an incrementing counter next to your first `"clicked!"` log. +Agora se você clica no quadrado, deve ver um registro dizendo `"clicked!"` na aba *Console* na parte inferior da seção *Navegador* do CodeSandbox. Clicar no quadrado mais de uma vez irá registrar `"clicked!"` novamente. Registros repetidos no console com a mesma mensagem não criarão mais linhas no console. Em vez disso, você verá um contador incrementando próximo ao seu primeiro registro `"clicked!"`. -If you are following this tutorial using your local development environment, you need to open your browser's Console. For example, if you use the Chrome browser, you can view the Console with the keyboard shortcut **Shift + Ctrl + J** (on Windows/Linux) or **Option + ⌘ + J** (on macOS). +Se você está seguindo este tutorial usando o seu ambiente de desenvolvimento local, você precisa abrir o console de seu navegador. Por exemplo, se você usa o navegador Chrome, você pode ver o Console com o atalho de teclado **Shift + Ctrl + J** (no Windows/Linux) ou **Option + ⌘ + J** (no macOS). -As a next step, you want the Square component to "remember" that it got clicked, and fill it with an "X" mark. To "remember" things, components use *state*. +Como um próximo passo, você quer que o componente Square "lembre-se" de que ele foi clicado, e preenchê-lo com uma marca de "X". Para "lembrar-se" de coisas, componentes usam *state*. -React provides a special function called `useState` that you can call from your component to let it "remember" things. Let's store the current value of the `Square` in state, and change it when the `Square` is clicked. +O React fornece uma função especial chamada `useState` a qual você pode chamar a partir de seu componente para permitir que ele "lembre-se" de coisas. Vamos armazenar o valor atual do `Square` em *state*, e mudá-lo quando o `Square` for clicado. -Import `useState` at the top of the file. Remove the `value` prop from the `Square` component. Instead, add a new line at the start of the `Square` that calls `useState`. Have it return a state variable called `value`: +Importe `useState` no topo do arquivo. Remova a *prop* `value` do componente `Square`. Em vez disso, adicione uma nova linha no começo de `Square` que chame `useState`. Faça com que ela retorne uma variável de *state* chamada `value`: ```js {1,3,4} import { useState } from 'react'; @@ -747,9 +747,9 @@ function Square() { //... ``` -`value` stores the value and `setValue` is a function that can be used to change the value. The `null` passed to `useState` is used as the initial value for this state variable, so `value` here starts off equal to `null`. +`value` salva o valor e `setValue` é a função que pode ser usada para mudar esse valor. O `null` passado para `useState` é usado como o valor inicial desta variável de *state*, então aqui `value` começa sendo igual a `null`. -Since the `Square` component no longer accepts props anymore, you'll remove the `value` prop from all nine of the Square components created by the Board component: +Já que o componente `Square` não mais aceita *props*, você irá remover a *prop* `value` de todos os nove componentes Square criados pelo componente Board: ```js {6-8,11-13,16-18} // ... @@ -776,7 +776,7 @@ export default function Board() { } ``` -Now you'll change `Square` to display an "X" when clicked. Replace the `console.log("clicked!");` event handler with `setValue('X');`. Now your `Square` component looks like this: +Agora você irá mudar `Square` para que exiba um "X" quando clicado. Substitua o manipulador de eventos `console.log("clicked!");` com `setValue('X');`. Agora o seu componente `Square` se parece com isto: ```js {5} function Square() { @@ -797,13 +797,13 @@ function Square() { } ``` -By calling this `set` function from an `onClick` handler, you're telling React to re-render that `Square` whenever its `