diff --git a/beta/src/content/learn/tutorial-tic-tac-toe.md b/beta/src/content/learn/tutorial-tic-tac-toe.md index d0c6f7598..b83bce5ae 100644 --- a/beta/src/content/learn/tutorial-tic-tac-toe.md +++ b/beta/src/content/learn/tutorial-tic-tac-toe.md @@ -1,31 +1,31 @@ --- -title: 'Tutorial: Tic-Tac-Toe' +title: 'Tutorial: Tres en línea' --- -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. +En este tutorial construirás un pequeño juego de Tres en linea. Este tutorial no asume ningún conocimiento previo de React. Las técnicas que aprenderás en el tutorial son fundamentales para crear cualquier aplicación de React, y comprenderlas por completo te dará una comprensión profunda de 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 fue diseñado para personas que prefieren **aprender haciendo** y quieren ver algo tangible de manera rápida. Si prefieres aprender cada concepto paso a paso, comienza con [Describir la UI.](/learn/describing-the-ui) -The tutorial is divided into several sections: +El tutorial se divide en varias secciones: -- [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. +- [Configuración para el tutorial](#setup-for-the-tutorial) te dará **un punto de partida** para seguir el tutorial. +- [Descripción general](#overview) te enseñará **los fundamentos** de React: componentes, props y estado. +- [Completar el juego](#completing-the-game) te enseñará **las técnicas más comunes** en el desarrollo de React. +- [Agregar viajes en el tiempo](#adding-time-travel) te brindará **una visión más profunda** de las fortalezas únicas de React. -### What are you building? {/*what-are-you-building*/} +### ¿Qué estás construyendo? {/*what-are-you-building*/} -In this tutorial, you'll build an interactive tic-tac-toe game with React. +En este tutorial, crearás un juego interactivo de Tres en línea con React. -You can see what it will look like when you're finished here: +Puedes ver cómo se verá cuando hayas terminado aquí: @@ -57,9 +57,9 @@ function Board({ xIsNext, squares, onPlay }) { const winner = calculateWinner(squares); let status; if (winner) { - status = 'Winner: ' + winner; + status = 'Ganador: ' + winner; } else { - status = 'Next player: ' + (xIsNext ? 'X' : 'O'); + status = 'Siguiente jugador: ' + (xIsNext ? 'X' : 'O'); } return ( @@ -103,9 +103,9 @@ export default function Game() { const moves = history.map((squares, move) => { let description; if (move > 0) { - description = 'Go to move #' + move; + description = 'Ir al movimiento #' + move; } else { - description = 'Go to game start'; + description = 'Ir al inicio del juego'; } return (
  • @@ -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. +Si el código aún no tiene sentido para ti, o si no estás familiarizado con la sintaxis del código, ¡no te preocupes! El objetivo de este tutorial es ayudarte a comprender React y su sintaxis. -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. +Te recomendamos que consultes el juego de Tres en línea anterior antes de continuar con el tutorial. Una de las características que notarás es que hay una lista numerada a la derecha del tablero del juego. Esta lista te brinda un historial de todos los movimientos que se han producido en el juego y se actualiza a medida que avanza el juego. -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. +Una vez que hayas jugado un poco con el juego Tres en línea terminado, sigue desplazándote. Comenzarás con una plantilla más simple en este tutorial. Nuestro siguiente paso es prepararte para que puedas comenzar a construir el juego. -## Setup for the tutorial {/*setup-for-the-tutorial*/} +## Configuración para el 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 allows you to write code in your browser and immediately view 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. +En el editor de código en vivo a continuación, haz clic en **Fork** en la esquina superior derecha para abrir el editor en una nueva pestaña usando el sitio web CodeSandbox. CodeSandbox te permite escribir código en su navegador e inmediatamente ver cómo sus usuarios verán la aplicación que ha creado. La nueva pestaña debería mostrarte un cuadrado vacío y el código de inicio 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: +También puedes seguir este tutorial utilizando tu entorno de desarrollo local. Para hacer esto, necesitas: -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/es/) +2. En la pestaña CodeSandbox que abriste anteriormente, presiona el botón de la esquina superior izquierda para abrir el menú y luego selecciona **Archivo > Exportar a ZIP** en ese menú para descargar un archivo comprimido de los archivos que necesitaras para realizar este tutorial. +3. Descomprime el archivo, luego abre la terminal y digita `cd` en el directorio que descomprimiste +4. Instala las dependencias con el comando `npm install` +5. Ejecuta el comando `npm start` para iniciar un servidor local y sigue las indicaciones para ver el código que se ejecuta en un navegador -If you get stuck, don't let this stop you! Follow along online instead and try a local setup again later. +Si te quedas atascado, ¡no dejes que esto te detenga! Siga en línea en su lugar e intenta una configuración local nuevamente más tarde. -## Overview {/*overview*/} +## Descripción general {/*overview*/} -Now that you're set up, let's get an overview of React! +Ahora que está configurado, veamos una descripción general de React. -### Inspecting the starter code {/*inspecting-the-starter-code*/} +### Inspeccionar el código de inicio {/*inspecting-the-starter-code*/} -In CodeSandbox you'll see three main sections: +En CodeSandbox verás tres secciones principales: -![CodeSandbox with starter code](../images/tutorial/react-starter-code-codesandbox.png) +![CodeSandbox con código de inicio](../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. La sección *Files* con una lista de archivos como `App.js`, `index.js`, `styles.css` y una carpeta llamada `public` +2. El *code editor* donde verás el código fuente de tu archivo seleccionado +3. La sección *browser* donde verás cómo se mostrará el código que has escrito -The `App.js` file should be selected in the _Files_ section. The contents of that file in the _code editor_ should be: +El archivo `App.js` debe seleccionarse en la sección *Files*. El contenido de ese archivo en el *code editor* debería 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: +La sección del *browser* debería mostrarte un cuadrado con una X como esta: -![x-filled square](../images/tutorial/x-filled-square.png) +![Cuadrado lleno de x](../images/tutorial/x-filled-square.png) -Now let's have a look at the files in the starter code. +Ahora echemos un vistazo a los archivos en el código de inicio. #### `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: +El código en `App.js` crea un *component*. En React, un componente es una pieza de código reutilizable que representa una parte de una interfaz de usuario. Los componentes se utilizan para representar, administrar y actualizar los elementos de la interfaz de usuario en su aplicación. Miremos el componente línea por línea para ver qué está pasando: ```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. +La primera línea define una función llamada `Square`. La palabra clave de JavaScript `export` hace que esta función sea accesible fuera de este archivo. La palabra clave `default` le dice a otros archivos que usan su código que es la función principal en su archivo. ```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. +La segunda línea devuelve un botón. La palabra clave de JavaScript `return` significa que lo que viene después se devuelve como un valor a la persona que llama a la función. `` cierra el elemento JSX para indicar que ningún contenido siguiente debe colocarse dentro del botón. #### `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. +Haz clic en el archivo llamado `styles.css` en la sección *Files* de CodeSandbox. Este archivo define los estilos para tu aplicación React. Los primeros dos *selectores CSS* (`*` y `body`) definen el estilo de grandes partes de su aplicación, mientras que el selector `.square` define el estilo de cualquier componente donde la propiedad `className` está establecida en `square`. En tu código, eso coincidiría con el botón de tu componente Square en el archivo `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. +Haz clic en el archivo llamado `index.js` en la sección *Files* de CodeSandbox. No editarás este archivo durante el tutorial, pero es este el puente entre el componente que creaste en el archivo `App.js` y el navegador web. ```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: +Las líneas 1-5 reúnen todas las piezas necesarias: -* React -* React's library to talk to web browsers (React DOM) -* the styles for your components -* the component you created in `App.js`. +- React +- Biblioteca de React para hablar con los navegadores web (React DOM) +- los estilos para tus componentes +- el componente que creaste en `App.js`. -The remainder of the file brings all the pieces together and injects the final product into `index.html` in the `public` folder. +El resto del archivo reúne todas las piezas e inyecta el producto final en `index.html` en la carpeta `public`. -### Building the board {/*building-the-board*/} +### Construyendo el tablero {/*building-the-board*/} -Let's get back to `App.js`. This is where you'll spend the rest of the tutorial. +Volvamos a `App.js`. Aquí es donde pasarás el resto del 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: +Actualmente, el tablero es solo un cuadrado, ¡pero necesitas nueve! Si solo intentas copiar y pegar tu cuadrado para hacer dos cuadrados como este: ```js {2} export default function Square() { @@ -358,7 +358,7 @@ export default function Square() { } ``` -You'll get this error: +Obtendrás este error: @@ -366,7 +366,7 @@ You'll get this error: -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: +Los componentes de React deben devolver un solo elemento JSX y no múltiples elementos JSX adyacentes como dos botones. Para solucionar esto, puedes usar *fragmentos* (`<>` y ``) para envolver múltiples elementos JSX adyacentes como este: ```js {3-6} export default function Square() { @@ -379,17 +379,17 @@ export default function Square() { } ``` -Now you should see: +Ahora deberías ver: -![two x-filled squares](../images/tutorial/two-x-filled-squares.png) +![dos cuadrados llenos de x](../images/tutorial/two-x-filled-squares.png) -Great! Now you just need to copy-paste a few times to add nine squares and... +¡Excelente! Ahora solo necesitas copiar y pegar varias veces para agregar nueve cuadrados y... -![nine x-filled squares in a line](../images/tutorial/nine-x-filled-squares.png) +![nueve cuadrados llenos de x en una línea](../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. +¡Oh, no! Los cuadrados están todos en una sola línea, no en una cuadrícula como la que necesitamos para nuestro tablero. Para solucionar esto, deberás agrupar tus cuadrados en filas con `div`s y agregar algunas clases de CSS. Mientras lo haces, le darás a cada cuadrado un número para asegurarse de saber dónde se muestra cada cuadrado. -In the `App.js` file, update the `Square` component to look like this: +En el archivo `App.js`, actualiza el componente `Square` para que se vea así: ```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: +El CSS definido en `styles.css` diseña los `div`s con `className` de `board-row`. Ahora que agrupaste tus componentes en filas con el estilo `div`s, tienes un tablero de tres en linea: -![tic-tac-toe board filled with numbers 1 through 9](../images/tutorial/number-filled-board.png) +![El tablero de Tres en linea esta lleno con números del 1 al 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`: +Pero ahora tienes un problema. Tu componente llamado `Square`, en realidad ya no es un cuadrado. Arreglemos esto cambiando el nombre a `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: +En este punto, tu código debería verse así: @@ -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 to only copy the code that you've manually typed at least once yourself. +Psssst... ¡Eso es mucho para escribir! Está bien copiar y pegar el código de esta página. Sin embargo, si estás preparado para un pequeño desafío, te recomendamos que solo copies el código que haz escrito manualmente al menos una vez. -### Passing data through props {/*passing-data-through-props*/} +### Pasar datos a travé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. +A continuación, querrás cambiar el valor de un cuadrado de vacío a "X" cuando el usuario haga clic en el cuadrado. Con la forma en que ha construido el tablero hasta ahora, necesitarías copiar y pegar el código que actualiza el cuadrado nueve veces (¡una vez por cada cuadrado que tengas)! En lugar de copiar y pegar, la arquitectura de componentes de React te permite crear un componente reutilizable para evitar el código duplicado desordenado. -First, you are going to copy the line defining your first square (``) from your `Board` component into a new `Square` component: +Primero, ve a copiar la línea que define el primer cuadrado (``) de tu componente `Board` en un nuevo 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: +Luego, actualiza el componente Board para renderizar ese componente `Square` usando la sintaxis JSX: ```js {5-19} // ... @@ -551,15 +551,15 @@ export default function Board() { } ``` -Notice how unlike the browser `div`s, your own components `Board` and `Square` must start with a capital letter. +Observa cómo, a diferencia de los `div`s del navegador, tus propios componentes `Board` y `Square` deben comenzar con una letra mayúscula. -Let's take a look: +Vamos a ver: -![one-filled board](../images/tutorial/board-filled-with-ones.png) +![tablero lleno](../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 the child component (`Square`). +¡Oh, no! Perdiste los cuadrados numerados que tenías antes. Ahora cada cuadrado dice "1". Para arreglar esto, utiliza las *props* para pasar el valor que debe tener cada cuadrado del componente principal (`Board`) al componente secundario (`Square`). -Update the `Square` component to read the `value` prop that you'll pass from the `Board`: +Actualiza el componente `Square` para leer la propiedad `value` que pasarás desde el `Tablero`: ```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 al componente Square se le puede pasar un objeto llamado `value`. -Now you want to display that `value` instead of `1` inside every square. Try doing it like this: +Ahora deseas mostrar ese `value` en lugar de `1` dentro de cada cuadrado. Intenta hacerlo así: ```js {2} function Square({ value }) { @@ -577,11 +577,11 @@ function Square({ value }) { } ``` -Oops, this is not what you wanted: +Vaya, esto no es lo que querías: -![value-filled board](../images/tutorial/board-filled-with-value.png) +![tablero lleno de valores](../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: +Querías representar la variable de JavaScript llamada `value` de tu componente, no la palabra "valor". Para "escapar a JavaScript" desde JSX, necesitas llaves. Agrega llaves alrededor de `value` en JSX de esta manera: ```js {2} function Square({ value }) { @@ -589,11 +589,11 @@ function Square({ value }) { } ``` -For now, you should see an empty board: +Por ahora, deberías ver un tablero vacío: -![empty board](../images/tutorial/empty-board.png) +![tablero vacío](../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: +Esto se debe a que el componente `Board` aún no ha pasado la prop `value` a cada componente `Square` que representa. Para solucionarlo, agrega el complemento `value` a cada componente `Square` representado por el 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: +Ahora deberías ver una cuadrícula de números nuevamente: -![tic-tac-toe board filled with numbers 1 through 9](../images/tutorial/number-filled-board.png) +![tablero de Tres en linea lleno de números del 1 al 9](../images/tutorial/number-filled-board.png) -Your updated code should look like this: +Tu código actualizado debería verse así: @@ -702,14 +702,14 @@ body { -### Making an interactive component {/*making-an-interactive-component*/} +### Haciendo un componente interactivo. {/*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` component: +Rellenemos el componente `Square` con una `X` al hacer clic en él. Declara una función llamada `handleClick` dentro del `Square`. Luego, agrega `onClick` a las props del elemento `