diff --git a/beta/src/pages/learn/add-react-to-a-website.md b/beta/src/pages/learn/add-react-to-a-website.md index 0d810ea13..6b1487880 100644 --- a/beta/src/pages/learn/add-react-to-a-website.md +++ b/beta/src/pages/learn/add-react-to-a-website.md @@ -1,22 +1,22 @@ --- -title: Add React to a Website +title: Añadir React a un sitio web --- <Intro> -React has been designed from the start for gradual adoption, and you can use as little or as much React as you need. Whether you're working with micro-frontends, an existing system, or just giving React a try, you can start adding interactive React components to an HTML page with just a few lines of code—and no build tooling! +React se ha diseñado desde un inicio para una adopción gradual, así puedes usar tan poco o mucho de React como necesites. Ya sea que estás trabajando con *micro-frontends*, un sistema existente o simplemente probando React, puedes empezar a añadir componentes interactivos de React a una página HTML con solo unas pocas líneas de código- ¡y sin herramientas para compilar! </Intro> -## Add React in one minute {/*add-react-in-one-minute*/} +## Añade React en un minuto {/*add-react-in-one-minute*/} -You can add a React component to an existing HTML page in under a minute. Try this out with your own website or [an empty HTML file](https://gist.github.com/rachelnabors/7b33305bf33776354797a2e3c1445186/archive/859eac2f7079c9e1f0a6eb818a9684a464064d80.zip)—all you need is an internet connection and a text editor like Notepad (or VSCode—check out our guide on [how to set yours up](/learn/editor-setup/))! +Puedes añadir componentes de React a una página HTML existente en menos de un minuto. Pruébalo con tu propio sitio web [o un archivo HTML vacío](https://gist.github.com/rachelnabors/7b33305bf33776354797a2e3c1445186/archive/859eac2f7079c9e1f0a6eb818a9684a464064d80.zip)—todo lo que necesitas es una conexión a internet y un editor de texto como Notepad (o VSCode-¡chequea nuestra guía sobre [cómo puedes configurar el tuyo](/learn/editor-setup/)!). -### Step 1: Add an element to the HTML {/*step-1-add-an-element-to-the-html*/} +### Paso 1: Añade un elemento al HTML {/*step-1-add-an-element-to-the-html*/} -In the HTML page you want to edit, add an HTML element like an empty `<div>` tag with a unique `id` to mark the spot where you want to display something with React. +En la página HTML que quieres editar, añade un elemento HTML, algo como una etiqueta `<div>` vacía con un `id` único que marque el lugar dónde quieres mostrar algo en React. -You can place a "container" element like this `<div>` anywhere inside the `<body>` tag. React will replace any existing content inside HTML elements, so they are usually empty. You can have as many of these HTML elements on one page as you need. +Puedes ubicar un elemento «contenedor» como este `<div>` en cualquier lugar dentro de la etiqueta `<body>`. React reemplazará cualquier contenido existente dentro de los elementos HTML, así que por lo general están vacíos. Puedes tener tantos de estos elementos HTML en una página como lo necesites. ```html {3} <!-- ... existing HTML ... --> @@ -26,17 +26,17 @@ You can place a "container" element like this `<div>` anywhere inside the `<body <!-- ... existing HTML ... --> ``` -### Step 2: Add the Script Tags {/*step-2-add-the-script-tags*/} +### Paso 2: Añade las etiquetas script {/*step-2-add-the-script-tags*/} -In the HTML page, right before the closing `</body>` tag, add three `<script>` tags for the following files: +En la página HTML, justo antes de cerrar la etiqueta `</body>`, añade tres etiquetas `<script>` para los siguientes archivos: -- [**react.development.js**](https://unpkg.com/react@18/umd/react.development.js) loads the core of React -- [**react-dom.development.js**](https://unpkg.com/react-dom@18/umd/react-dom.development.js) lets React render HTML elements to the [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model). -- **like_button.js** is where you'll write your component in step 3! +- [**react.development.js**](https://unpkg.com/react@18/umd/react.development.js) carga el núcleo de React +- [**react-dom.development.js**](https://unpkg.com/react-dom@18/umd/react-dom.development.js) le permite a React renderizar elementos HTML en el [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model). +- **like_button.js** ¡Es dónde escribirás tu componente en el paso 3! <Gotcha> -When deploying, replace "development.js" with "production.min.js". +Al desplegar, reemplaza "development.js" con "production.min.js". </Gotcha> @@ -48,9 +48,9 @@ When deploying, replace "development.js" with "production.min.js". </body> ``` -### Step 3: Create a React component {/*step-3-create-a-react-component*/} +### Paso 3: Crea un componente de React {/*step-3-create-a-react-component*/} -Create a file called **like_button.js** next to your HTML page, add this code snippet, and save the file. This code defines a React component called `LikeButton`. [You can learn more about making components in our guides.](/learn/your-first-component) +Crea un archivo que se llame **like_button.js** junto a tu página HTML, añade este fragmento de código y guarda el archivo. Este código define un componente de React llamado `LikeButton`. [Puedes aprender más sobre como hacer componentes en nuestras guías.](/learn/your-first-component) ```js 'use strict'; @@ -72,9 +72,9 @@ function LikeButton() { } ``` -### Step 4: Add your React Component to the page {/*step-4-add-your-react-component-to-the-page*/} +### Paso 4: Añade tu componente de React a la página {/*step-4-add-your-react-component-to-the-page*/} -Lastly, add three lines to the bottom of **like_button.js**. These three lines of code find the `<div>` you added to your HTML in the first step, create a React app with it, and then display the "Like" button React component inside of it. +Por último, añade tres líneas al final de **like_button.js**. Estas tres líneas de código se encargan de encontrar el `<div>` que has añadido a tu HTML en el primer paso, crear una aplicación de React con él y luego mostrar el componente de React del botón «Like» dentro de ella. ```js const domContainer = document.getElementById('component-goes-here'); @@ -82,17 +82,17 @@ const root = ReactDOM.createRoot(domContainer); root.render(React.createElement(LikeButton)); ``` -**Congratulations! You have just rendered your first React component to your website!** +**¡Felicidades! ¡Acabas de renderizar tu primer componente de React en tu sitio web!** -- [View the full example source code](https://gist.github.com/rachelnabors/c64b3aeace8a191cf5ea6fb5202e66c9) -- [Download the full example (2KB zipped)](https://gist.github.com/rachelnabors/c64b3aeace8a191cf5ea6fb5202e66c9/archive/7b41a88cb1027c9b5d8c6aff5212ecd3d0493504.zip) +- [Mira el código fuente completo del ejemplo](https://gist.github.com/rachelnabors/c64b3aeace8a191cf5ea6fb5202e66c9) +- [Descarga el ejemplo completo (2KB comprimido con zip)](https://gist.github.com/rachelnabors/c64b3aeace8a191cf5ea6fb5202e66c9/archive/7b41a88cb1027c9b5d8c6aff5212ecd3d0493504.zip) -#### You can reuse components! {/*you-can-reuse-components*/} +#### ¡Puedes reutilizar componentes! {/*you-can-reuse-components*/} -You might want to display a React component in multiple places on the same HTML page. This is most useful while React-powered parts of the page are isolated from each other. You can do this by calling `ReactDOM.createRoot()` multiple times with multiple container elements. +Puede que quieras mostrar un componente de React en múltiples lugares en la misma página HTML. Esto es sobre todo más útil cuando las partes de la página controladas por React están aisladas unas de otras. Puedes hacerlo llamando a `ReactDOM.createRoot()` en múltiples elementos contenedores. -1. In **index.html**, add an additional container element `<div id="component-goes-here-too"></div>`. -2. In **like_button.js**, add an additional `ReactDOM.render()` for the new container element: +1. En **index.html**, añade un elemento contenedor adicional `<div id="component-goes-here-too"></div>`. +2. En **like_button.js**, añade un `ReactDOM.render()` adicional para el nuevo elemento contenedor: ```js {6,7,8,9} const root1 = ReactDOM.createRoot( @@ -106,41 +106,41 @@ const root2 = ReactDOM.createRoot( root2.render(React.createElement(LikeButton)); ``` -Check out [an example that displays the "Like" button three times and passes some data to it](https://gist.github.com/rachelnabors/c0ea05cc33fbe75ad9bbf78e9044d7f8)! +¡Mira [un ejemplo que muestra el botón «Like» tres veces y le pasa algunos datos](https://gist.github.com/rachelnabors/c0ea05cc33fbe75ad9bbf78e9044d7f8)!(https://gist.github.com/rachelnabors/c0ea05cc33fbe75ad9bbf78e9044d7f8)! -### Step 5: Minify JavaScript for production {/*step-5-minify-javascript-for-production*/} +### Paso 5: Minifica JavaScript para producción {/*step-5-minify-javascript-for-production*/} -Unminified JavaScript can significantly slow down page load times for your users. Before deploying your website to production, it's a good idea to minify its scripts. +El código no minificado de JavaScript puede ralentizar significativamente los tiempos de carga para tus usuarios. Antes de desplegar tu sitio web a producción es una buena idea minificar sus scripts. -- **If you don't have a minification step** for your scripts, [here's one way to set it up](https://gist.github.com/gaearon/42a2ffa41b8319948f9be4076286e1f3). -- **If you already minify** your application scripts, your site will be production-ready if you ensure that the deployed HTML loads the versions of React ending in `production.min.js` like so: +- **Si no tienes un paso de minificación** para tus scripts, [aquí hay una forma de configurarlo](https://gist.github.com/gaearon/42a2ffa41b8319948f9be4076286e1f3). +- **Si ya estás minificando** los scripts de tu aplicación, tu sitio estará listo para producción si te aseguras de que el HTML desplegado carga las versiones de React que terminan en `production.min.js`, como estas: ```html <script src="https://unpkg.com/react@18/umd/react.production.min.js" crossorigin></script> <script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js" crossorigin></script> ``` -## Try React with JSX {/*try-react-with-jsx*/} +## Prueba React con JSX {/*try-react-with-jsx*/} -The examples above rely on features that are natively supported by browsers. This is why **like_button.js** uses a JavaScript function call to tell React what to display: +Los ejemplos de arriba dependen de funcionalidades que son compatibles de forma nativa con los navegadores. Es por esto que **like_button.js** utiliza una llamada a una función para decirle a React qué tiene que mostrar: ```js return React.createElement('button', {onClick: () => setLiked(true)}, 'Like'); ``` -However, React also offers an option to use [JSX](/learn/writing-markup-with-jsx), an HTML-like JavaScript syntax, instead: +Sin embargo, React también ofrece una opción para usar [JSX](/learn/writing-markup-with-jsx), una sintaxis de JavaScript similar a HTML. Permite escribir: ```jsx return <button onClick={() => setLiked(true)}>Like</button>; ``` -These two code snippets are equivalent. JSX is popular syntax for describing markup in JavaScript. Many people find it familiar and helpful for writing UI code--both with React and with other libraries. You might see "markup sprinkled throughout your JavaScript" in other projects! +Estos dos fragmentos de código son equivalentes. JSX es una sintaxis popular para describir marcado en JavaScript. Muchas personas lo encuentran familiar y útil para escribir código de IU--tanto con React como con otras bibliotecas. ¡Puede que veas «marcado esparcido por tu JavaScript» en otros proyectos! -> You can play with transforming HTML markup into JSX using [this online converter](https://babeljs.io/en/repl#?babili=false&browsers=&build=&builtIns=false&spec=false&loose=false&code_lz=DwIwrgLhD2B2AEcDCAbAlgYwNYF4DeAFAJTw4B88EAFmgM4B0tAphAMoQCGETBe86WJgBMAXJQBOYJvAC-RGWQBQ8FfAAyaQYuAB6cFDhkgA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&timeTravel=false&sourceType=module&lineWrap=true&presets=es2015%2Creact%2Cstage-2&prettier=false&targets=&version=7.4.3). +> Puedes interactuar con la transformación de marcado HTML en JSX usando este [convertir en línea](https://babeljs.io/en/repl#?babili=false&browsers=&build=&builtIns=false&spec=false&loose=false&code_lz=DwIwrgLhD2B2AEcDCAbAlgYwNYF4DeAFAJTw4B88EAFmgM4B0tAphAMoQCGETBe86WJgBMAXJQBOYJvAC-RGWQBQ8FfAAyaQYuAB6cFDhkgA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&timeTravel=false&sourceType=module&lineWrap=true&presets=es2015%2Creact%2Cstage-2&prettier=false&targets=&version=7.4.3). -### Try JSX {/*try-jsx*/} +### Prueba JSX {/*try-jsx*/} -The quickest way to try JSX in your project is to add the Babel compiler to your page's `<head>` along with React and ReactDOM like so: +La forma más rápida de probar JSX en tu proyecto es añadir el compilador de Babel al `<head>` de tu página junto con React y ReactDOM de esta forma: ```html {6} <!-- ... rest of <head> ... --> @@ -154,7 +154,7 @@ The quickest way to try JSX in your project is to add the Babel compiler to your <!-- ... rest of <body> ... --> ``` -Now you can use JSX in any `<script>` tag by adding `type="text/babel"` attribute to it. For instance: +Ahora puedes usar JSX en cualquier etiqueta `<script>` si le añades el atributo `type="text/babel"`. Por ejemplo: ```jsx {1} <script type="text/babel"> @@ -163,9 +163,9 @@ Now you can use JSX in any `<script>` tag by adding `type="text/babel"` attribut </script> ``` -To convert **like_button.js** to use JSX: +Para convertir **like_button.js** para que use JSX: -1. In **like_button.js**, replace +1. En **like_button.js**, reemplaza ```js return React.createElement( @@ -177,63 +177,63 @@ return React.createElement( ); ``` -with: +con: ```jsx return <button onClick={() => setLiked(true)}>Like</button>; ``` -2. In **index.html**, add `type="text/babel"` to the like button's script tag: +2. En **index.html**, añade `type="text/babel"` a la etiqueta script del botón: ```html <script src="like_button.js" type="text/babel"></script> ``` -Here is [an example HTML file with JSX](https://raw.githubusercontent.com/reactjs/reactjs.org/main/static/html/single-file-example.html) that you can download and play with. +Aquí hay [un ejemplo de un archivo HTML con JSX](https://raw.githubusercontent.com/reactjs/reactjs.org/main/static/html/single-file-example.html) que puedes descargar y jugar con él. -This approach is fine for learning and creating simple demos. However, it makes your website slow and **isn't suitable for production**. When you're ready to move forward, remove this new `<script>` tag and the `type="text/babel"` attributes you've added. Instead, in the next section you will set up a JSX preprocessor to convert all your `<script>` tags automatically. +Esta forma está bien para aprender y crear demos sencillos. Sin embargo, ralentiza tu sitio web y **no es apropiada para producción**. Cuando estés listo para seguir adelante, elimina esta nueva etiqueta `<script>` y los atributos `type="text/babel"` que añadiste. En cambio, en la próxima sección configurarás un preprocesador JSX para convertir todas tus etiquetas `<script>` automáticamente. -### Add JSX to a project {/*add-jsx-to-a-project*/} +### Añade JSX a un proyecto {/*add-jsx-to-a-project*/} -Adding JSX to a project doesn't require complicated tools like a [bundler](/learn/start-a-new-react-project#custom-toolchains) or a development server. Adding a JSX preprocessor is a lot like adding a CSS preprocessor. +Añadir JSX a un proyecto no requiere herramientas complicadas como un [*bundler* (empaquetador)](/learn/start-a-new-react-project#custom-toolchains) o un servidor de desarrollo. Añadir un preprocesador de JSX es bastante parecido a añadir un preprocesador de CSS. -Go to your project folder in the terminal, and paste these two commands (**Be sure you have [Node.js](https://nodejs.org/) installed!**): +Ve a la carpeta de tu proyecto en la terminal, y pega estos dos comandos (**¡Asegúrate de tener instalado [Node.js](https://nodejs.org/)!**): -1. `npm init -y` (if it fails, [here's a fix](https://gist.github.com/gaearon/246f6380610e262f8a648e3e51cad40d)) +1. `npm init -y` (si falla, [aquí hay una solución](https://gist.github.com/gaearon/246f6380610e262f8a648e3e51cad40d)) 2. `npm install babel-cli@6 babel-preset-react-app@3` -You only need npm to install the JSX preprocessor. You won't need it for anything else. Both React and the application code can stay as `<script>` tags with no changes. +Solo necesitas npm para instalar el preprocesador de JSX. No lo necesitarás para nada más. Tanto React como el código de la aplicación se pueden quedar como etiquetas `<script>` sin cambios. -Congratulations! You just added a **production-ready JSX setup** to your project. +¡Felicidades! Acabas de añadir una **configuración de JSX lista para producción** a tu proyecto. -### Run the JSX Preprocessor {/*run-the-jsx-preprocessor*/} +### Corre el preprocesador de JSX {/*run-the-jsx-preprocessor*/} -You can preprocess JSX so that every time you save a file with JSX in it, the transform will be re-run, converting the JSX file into a new, plain JavaScript file. +Puedes preprocesar JSX de forma tal que cada vez que guardes un archivo con JSX dentro, la transformación se vuelva a ejecutar y convierta el JSX en un archivo nuevo con JavaScript simple. -1. Create a folder called **src** -2. In your terminal, run this command: `npx babel --watch src --out-dir . --presets react-app/prod ` (Don't wait for it to finish! This command starts an automated watcher for JSX.) -3. Move your JSX-ified **like_button.js** to the new **src** folder (or create a **like_button.js** containing this [JSX starter code](https://gist.githubusercontent.com/rachelnabors/ffbc9a0e33665a58d4cfdd1676f05453/raw/652003ff54d2dab8a1a1e5cb3bb1e28ff207c1a6/like_button.js)) +1. Crea una carpeta llamada **src** +2. En tu terminal, ejecuta este comando: `npx babel --watch src --out-dir . --presets react-app/prod ` (¡No esperes a que termine! Este comando inicia un *watcher* (observador) automático para JSX). +3. Mueve tu **like_button.js** con JSX a la nueva carpeta **src** (o crea un **like_button.js** que contenga este [código JSX para iniciar](https://gist.githubusercontent.com/rachelnabors/ffbc9a0e33665a58d4cfdd1676f05453/raw/652003ff54d2dab8a1a1e5cb3bb1e28ff207c1a6/like_button.js)) -The watcher will create a preprocessed **like_button.js** with the plain JavaScript code suitable for the browser. +El *watcher* creará un **like_button.js** preprocesado con el código JavaScript simple que es adecuado para un navegador. <Gotcha> -If you see an error message saying "You have mistakenly installed the `babel` package", you might have missed [the previous step](#add-jsx-to-a-project). Perform it in the same folder, and then try again. +Si ves un mensaje de error que dice «*You have mistakenly installed the `babel` package* (has instalado erróneamente el paquete babel)», puede que te haya faltado [el paso previo](#add-jsx-to-a-project). Realízalo en la misma carpeta y luego inténtalo nuevamente. </Gotcha> -As a bonus, this also lets you use modern JavaScript syntax features like classes without worrying about breaking older browsers. The tool we just used is called Babel, and you can learn more about it from [its documentation](https://babeljs.io/docs/en/babel-cli/). +Como un plus, esto también te permite utilizar funcionalidades de sintaxis de JavaScript moderno como las clases sin tener que preocuparte por causar errores en navegadores antiguos. La herramienta que acabamos de usar se llama Babel y puedes aprender más sobre ella en [su documentación](https://babeljs.io/docs/en/babel-cli/). -If you're getting comfortable with build tools and want them to do more for you, [we cover some of the most popular and approachable toolchains here](/learn/start-a-new-react-project). +Si te empiezas a sentir cómodo con las herramientas de construcción y quieres que hagan más por ti, [cubrimos algunas de las más populares y accesibles aquí](/learn/start-a-new-react-project). <DeepDive title="React without JSX"> -Originally JSX was introduced to make writing components with React feel as familiar as writing HTML. Since then, the syntax has become widespread. However, there may be instances where you do not want to use or cannot use JSX. You have two options: +Originalmente JSX se introdujo para que escribir componentes con React se sintiera tan familiar como escribir HTML. Desde entonces, la sintaxis se ha generalizado. Sin embargo, hay momentos en que no quieres o no puedes usar JSX. Tienes dos opciones: -- Use a JSX alternative like [htm](https://github.com/developit/htm) which doesn't use a compiler—it uses JavaScript's native Tagged Templates. -- Use [`React.createElement()`](/apis/createelement), which has a special structure explained below. +- Usar una alternativa como [htm](https://github.com/developit/htm) que no usa un compilador-utiliza las plantillas etiquetadas, nativas en JavaScript. +- Usar [`React.createElement()`](/apis/createelement), que tiene una estructura especial que se explica debajo. -With JSX, you would write a component like so: +Con JSX, escribirías un componete de esta forma: ```jsx function Hello(props) { @@ -243,7 +243,7 @@ function Hello(props) { ReactDOM.render(<Hello toWhat="World" />, document.getElementById('root')); ``` -With `React.createElement()`, you would write it like this: +Con `React.createElement()`, lo escribirías así: ```js function Hello(props) { @@ -256,13 +256,13 @@ ReactDOM.render( ); ``` -It accepts three arguments: `React.createElement(component, props, children)`. Here's how they work: +Acepta tres argumentos: `React.createElement(component, props, children)`. Funcionan así: -1. A **component**, which can be a string representing an HTML element or a function component -2. An object of any [**props** you want to pass](/learn/passing-props-to-a-component) -3. An object of any **children** the component might have, such as text strings +1. Un **componente**, que puede ser una cadena representando un elemento HTML o un componente de función +2. Un objeto de todas las [**props** que deseas pasar](/learn/passing-props-to-a-component) +3. Un objeto de todos los *hijos* que el componente puede tener, como cadenas de texto -If you get tired of typing `React.createElement()`, one common pattern is to assign a shorthand: +Si te cansas de escribir `React.createElement()`, un patrón común es asignar una forma abreviada: ```js const e = React.createElement; @@ -270,6 +270,6 @@ const e = React.createElement; ReactDOM.render(e('div', null, 'Hello World'), document.getElementById('root')); ``` -If you use this shorthand form for `React.createElement()`, it can be almost as convenient to use React without JSX. +Si utilizas esta forma abreviada para `React.createElement()`, puede ser casi tan conveniente utilizar React sin JSX. </DeepDive>