diff --git a/src/content/learn/creating-a-react-app.md b/src/content/learn/creating-a-react-app.md index df512cca8..b63c957f8 100644 --- a/src/content/learn/creating-a-react-app.md +++ b/src/content/learn/creating-a-react-app.md @@ -1,94 +1,94 @@ --- -title: Creating a React App +title: Crear una aplicación de React --- -If you want to build a new app or website with React, we recommend starting with a framework. +Si quieres crear una nueva aplicación o sitio web con React, te recomendamos comenzar con un framework. -If your app has constraints not well-served by existing frameworks, you prefer to build your own framework, or you just want to learn the basics of a React app, you can [build a React app from scratch](/learn/build-a-react-app-from-scratch). +Si tu aplicación tiene restricciones que no son bien atendidas por los frameworks existentes, prefieres construir tu propio framework, o simplemente quieres aprender lo básico de una aplicación de React, puedes [crear una aplicación de React desde cero](/learn/build-a-react-app-from-scratch). -## Full-stack frameworks {/*full-stack-frameworks*/} +## Frameworks full-stack {/*full-stack-frameworks*/} -These recommended frameworks support all the features you need to deploy and scale your app in production. They have integrated the latest React features and take advantage of React’s architecture. +Estos frameworks recomendados soportan todas las funcionalidades que necesitas para desplegar y escalar tu aplicación en producción. Han integrado las últimas funcionalidades de React y aprovechan la arquitectura de React. -#### Full-stack frameworks do not require a server. {/*react-frameworks-do-not-require-a-server*/} +#### Los frameworks full-stack no requieren un servidor. {/*react-frameworks-do-not-require-a-server*/} -All the frameworks on this page support client-side rendering ([CSR](https://developer.mozilla.org/en-US/docs/Glossary/CSR)), single-page apps ([SPA](https://developer.mozilla.org/en-US/docs/Glossary/SPA)), and static-site generation ([SSG](https://developer.mozilla.org/en-US/docs/Glossary/SSG)). These apps can be deployed to a [CDN](https://developer.mozilla.org/en-US/docs/Glossary/CDN) or static hosting service without a server. Additionally, these frameworks allow you to add server-side rendering on a per-route basis, when it makes sense for your use case. +Todos los frameworks en esta página soportan renderizado del lado del cliente ([CSR](https://developer.mozilla.org/en-US/docs/Glossary/CSR)), aplicaciones de una sola página ([SPA](https://developer.mozilla.org/en-US/docs/Glossary/SPA)) y generación de sitios estáticos ([SSG](https://developer.mozilla.org/en-US/docs/Glossary/SSG)). Estas aplicaciones pueden desplegarse en un [CDN](https://developer.mozilla.org/en-US/docs/Glossary/CDN) o servicio de hosting estático sin un servidor. Además, estos frameworks te permiten añadir renderizado del lado del servidor en base a cada ruta, cuando tenga sentido para tu caso de uso. -This allows you to start with a client-only app, and if your needs change later, you can opt-in to using server features on individual routes without rewriting your app. See your framework's documentation for configuring the rendering strategy. +Esto te permite comenzar con una aplicación solo del lado del cliente, y si tus necesidades cambian más adelante, puedes optar por usar funcionalidades del servidor en rutas individuales sin reescribir tu aplicación. Consulta la documentación de tu framework para configurar la estrategia de renderizado. ### Next.js (App Router) {/*nextjs-app-router*/} -**[Next.js's App Router](https://nextjs.org/docs) is a React framework that takes full advantage of React's architecture to enable full-stack React apps.** +**[El App Router de Next.js](https://nextjs.org/docs) es un framework de React que aprovecha al máximo la arquitectura de React para habilitar aplicaciones React full-stack.** npx create-next-app@latest -Next.js is maintained by [Vercel](https://vercel.com/). You can [deploy a Next.js app](https://nextjs.org/docs/app/building-your-application/deploying) to any hosting provider that supports Node.js or Docker containers, or to your own server. Next.js also supports [static export](https://nextjs.org/docs/app/building-your-application/deploying/static-exports) which doesn't require a server. +Next.js es mantenido por [Vercel](https://vercel.com/). Puedes [desplegar una aplicación de Next.js](https://nextjs.org/docs/app/building-your-application/deploying) en cualquier proveedor de hosting que soporte Node.js o contenedores Docker, o en tu propio servidor. Next.js también soporta [exportación estática](https://nextjs.org/docs/app/building-your-application/deploying/static-exports) que no requiere un servidor. ### React Router (v7) {/*react-router-v7*/} -**[React Router](https://reactrouter.com/start/framework/installation) is the most popular routing library for React and can be paired with Vite to create a full-stack React framework**. It emphasizes standard Web APIs and has several [ready to deploy templates](https://github.com/remix-run/react-router-templates) for various JavaScript runtimes and platforms. +**[React Router](https://reactrouter.com/start/framework/installation) es la biblioteca de enrutamiento más popular para React y puede combinarse con Vite para crear un framework React full-stack**. Enfatiza las APIs web estándar y tiene varias [plantillas listas para desplegar](https://github.com/remix-run/react-router-templates) para varios entornos de ejecución y plataformas de JavaScript. -To create a new React Router framework project, run: +Para crear un nuevo proyecto con el framework React Router, ejecuta: npx create-react-router@latest -React Router is maintained by [Shopify](https://www.shopify.com). +React Router es mantenido por [Shopify](https://www.shopify.com). -### Expo (for native apps) {/*expo*/} +### Expo (para aplicaciones nativas) {/*expo*/} -**[Expo](https://expo.dev/) is a React framework that lets you create universal Android, iOS, and web apps with truly native UIs.** It provides an SDK for [React Native](https://reactnative.dev/) that makes the native parts easier to use. To create a new Expo project, run: +**[Expo](https://expo.dev/) es un framework de React que te permite crear aplicaciones universales para Android, iOS y web con UIs verdaderamente nativas.** Proporciona un SDK para [React Native](https://reactnative.dev/) que hace que las partes nativas sean más fáciles de usar. Para crear un nuevo proyecto de Expo, ejecuta: npx create-expo-app@latest -If you're new to Expo, check out the [Expo tutorial](https://docs.expo.dev/tutorial/introduction/). +Si eres nuevo en Expo, consulta el [tutorial de Expo](https://docs.expo.dev/tutorial/introduction/). -Expo is maintained by [Expo (the company)](https://expo.dev/about). Building apps with Expo is free, and you can submit them to the Google and Apple app stores without restrictions. Expo additionally provides opt-in paid cloud services. +Expo es mantenido por [Expo (la empresa)](https://expo.dev/about). Crear aplicaciones con Expo es gratuito y puedes enviarlas a las tiendas de aplicaciones de Google y Apple sin restricciones. Expo además proporciona servicios en la nube de pago opcionales. -## Other frameworks {/*other-frameworks*/} +## Otros frameworks {/*other-frameworks*/} -There are other up-and-coming frameworks that are working towards our full stack React vision: +Hay otros frameworks emergentes que están trabajando hacia nuestra visión de React full-stack: -- [TanStack Start (Beta)](https://tanstack.com/): TanStack Start is a full-stack React framework powered by TanStack Router. It provides a full-document SSR, streaming, server functions, bundling, and more using tools like Nitro and Vite. -- [RedwoodJS](https://redwoodjs.com/): Redwood is a full stack React framework with lots of pre-installed packages and configuration that makes it easy to build full-stack web applications. +- [TanStack Start (Beta)](https://tanstack.com/): TanStack Start es un framework React full-stack potenciado por TanStack Router. Proporciona SSR de documento completo, streaming, funciones del servidor, empaquetado y más usando herramientas como Nitro y Vite. +- [RedwoodJS](https://redwoodjs.com/): Redwood es un framework React full-stack con muchos paquetes y configuraciones preinstaladas que facilitan la creación de aplicaciones web full-stack. -#### Which features make up the React team’s full-stack architecture vision? {/*which-features-make-up-the-react-teams-full-stack-architecture-vision*/} +#### ¿Qué funcionalidades componen la visión de arquitectura full-stack del equipo de React? {/*which-features-make-up-the-react-teams-full-stack-architecture-vision*/} -Next.js's App Router bundler fully implements the official [React Server Components specification](https://github.com/reactjs/rfcs/blob/main/text/0188-server-components.md). This lets you mix build-time, server-only, and interactive components in a single React tree. +El empaquetador del App Router de Next.js implementa completamente la [especificación oficial de React Server Components](https://github.com/reactjs/rfcs/blob/main/text/0188-server-components.md). Esto te permite mezclar componentes de tiempo de compilación, solo del servidor e interactivos en un único árbol de React. -For example, you can write a server-only React component as an `async` function that reads from a database or from a file. Then you can pass data down from it to your interactive components: +Por ejemplo, puedes escribir un componente React que solo se ejecuta en el servidor como una función `async` que lee de una base de datos o de un archivo. Luego puedes pasar los datos hacia abajo a tus componentes interactivos: ```js -// This component runs *only* on the server (or during the build). +// Este componente se ejecuta *solo* en el servidor (o durante la compilación). async function Talks({ confId }) { - // 1. You're on the server, so you can talk to your data layer. API endpoint not required. + // 1. Estás en el servidor, así que puedes comunicarte con tu capa de datos. No se necesita endpoint de API. const talks = await db.Talks.findAll({ confId }); - // 2. Add any amount of rendering logic. It won't make your JavaScript bundle larger. + // 2. Añade cualquier cantidad de lógica de renderizado. No hará más grande tu paquete de JavaScript. const videos = talks.map(talk => talk.video); - // 3. Pass the data down to the components that will run in the browser. + // 3. Pasa los datos hacia abajo a los componentes que se ejecutarán en el navegador. return ; } ``` -Next.js's App Router also integrates [data fetching with Suspense](/blog/2022/03/29/react-v18#suspense-in-data-frameworks). This lets you specify a loading state (like a skeleton placeholder) for different parts of your user interface directly in your React tree: +El App Router de Next.js también integra [obtención de datos con Suspense](/blog/2022/03/29/react-v18#suspense-in-data-frameworks). Esto te permite especificar un estado de carga (como un esqueleto de marcador de posición) para diferentes partes de tu interfaz de usuario directamente en tu árbol de React: ```js }> @@ -96,18 +96,18 @@ Next.js's App Router also integrates [data fetching with Suspense](/blog/2022/03 ``` -Server Components and Suspense are React features rather than Next.js features. However, adopting them at the framework level requires buy-in and non-trivial implementation work. At the moment, the Next.js App Router is the most complete implementation. The React team is working with bundler developers to make these features easier to implement in the next generation of frameworks. +Server Components y Suspense son funcionalidades de React en lugar de funcionalidades de Next.js. Sin embargo, adoptarlas a nivel de framework requiere aceptación y un trabajo de implementación no trivial. En este momento, el App Router de Next.js es la implementación más completa. El equipo de React está trabajando con desarrolladores de empaquetadores para hacer que estas funcionalidades sean más fáciles de implementar en la próxima generación de frameworks. -## Start From Scratch {/*start-from-scratch*/} +## Empezar desde cero {/*start-from-scratch*/} -If your app has constraints not well-served by existing frameworks, you prefer to build your own framework, or you just want to learn the basics of a React app, there are other options available for starting a React project from scratch. +Si tu aplicación tiene restricciones que no son bien atendidas por los frameworks existentes, prefieres construir tu propio framework, o simplemente quieres aprender lo básico de una aplicación de React, hay otras opciones disponibles para iniciar un proyecto de React desde cero. -Starting from scratch gives you more flexibility, but does require that you make choices on which tools to use for routing, data fetching, and other common usage patterns. It's a lot like building your own framework, instead of using a framework that already exists. The [frameworks we recommend](#full-stack-frameworks) have built-in solutions for these problems. +Empezar desde cero te da más flexibilidad, pero requiere que tomes decisiones sobre qué herramientas usar para el enrutamiento, la obtención de datos y otros patrones de uso comunes. Es muy parecido a construir tu propio framework, en lugar de usar uno que ya existe. Los [frameworks que recomendamos](#full-stack-frameworks) tienen soluciones integradas para estos problemas. -If you want to build your own solutions, see our guide to [build a React app from Scratch](/learn/build-a-react-app-from-scratch) for instructions on how to set up a new React project starting with a build tool like [Vite](https://vite.dev/), [Parcel](https://parceljs.org/), or [RSbuild](https://rsbuild.dev/). +Si quieres construir tus propias soluciones, consulta nuestra guía para [crear una aplicación de React desde cero](/learn/build-a-react-app-from-scratch) para instrucciones sobre cómo configurar un nuevo proyecto de React comenzando con una herramienta de compilación como [Vite](https://vite.dev/), [Parcel](https://parceljs.org/) o [RSbuild](https://rsbuild.dev/). ----- -_If you’re a framework author interested in being included on this page, [please let us know](https://github.com/reactjs/react.dev/issues/new?assignees=&labels=type%3A+framework&projects=&template=3-framework.yml&title=%5BFramework%5D%3A+)._ +_Si eres autor de un framework interesado en ser incluido en esta página, [por favor haznos saber](https://github.com/reactjs/react.dev/issues/new?assignees=&labels=type%3A+framework&projects=&template=3-framework.yml&title=%5BFramework%5D%3A+)._ diff --git a/src/content/reference/react/act.md b/src/content/reference/react/act.md index eff3f891f..1028bc665 100644 --- a/src/content/reference/react/act.md +++ b/src/content/reference/react/act.md @@ -4,7 +4,7 @@ title: act -`act` is a test helper to apply pending React updates before making assertions. +`act` es un auxiliar de pruebas para aplicar actualizaciones pendientes de React antes de realizar aserciones. ```js await act(async actFn) @@ -12,10 +12,10 @@ await act(async actFn) -To prepare a component for assertions, wrap the code rendering it and performing updates inside an `await act()` call. This makes your test run closer to how React works in the browser. +Para preparar un componente para las aserciones, envuelve el código que lo renderiza y realiza actualizaciones dentro de una llamada a `await act()`. Esto hace que tu prueba se ejecute de forma más parecida a cómo funciona React en el navegador. -You might find using `act()` directly a bit too verbose. To avoid some of the boilerplate, you could use a library like [React Testing Library](https://testing-library.com/docs/react-testing-library/intro), whose helpers are wrapped with `act()`. +Puede que encuentres que usar `act()` directamente es un poco verboso. Para evitar algo del código repetitivo, podrías usar una biblioteca como [React Testing Library](https://testing-library.com/docs/react-testing-library/intro), cuyos auxiliares están envueltos con `act()`. @@ -23,13 +23,13 @@ You might find using `act()` directly a bit too verbose. To avoid some of the bo --- -## Reference {/*reference*/} +## Referencia {/*reference*/} ### `await act(async actFn)` {/*await-act-async-actfn*/} -When writing UI tests, tasks like rendering, user events, or data fetching can be considered as “units” of interaction with a user interface. React provides a helper called `act()` that makes sure all updates related to these “units” have been processed and applied to the DOM before you make any assertions. +Al escribir pruebas de UI, tareas como el renderizado, eventos del usuario o la obtención de datos pueden considerarse como "unidades" de interacción con una interfaz de usuario. React proporciona un auxiliar llamado `act()` que se asegura de que todas las actualizaciones relacionadas con estas "unidades" hayan sido procesadas y aplicadas al DOM antes de realizar cualquier aserción. -The name `act` comes from the [Arrange-Act-Assert](https://wiki.c2.com/?ArrangeActAssert) pattern. +El nombre `act` proviene del patrón [Arrange-Act-Assert](https://wiki.c2.com/?ArrangeActAssert) (Organizar-Actuar-Afirmar). ```js {2,4} it ('renders with button disabled', async () => { @@ -42,25 +42,25 @@ it ('renders with button disabled', async () => { -We recommend using `act` with `await` and an `async` function. Although the sync version works in many cases, it doesn't work in all cases and due to the way React schedules updates internally, it's difficult to predict when you can use the sync version. +Recomendamos usar `act` con `await` y una función `async`. Aunque la versión síncrona funciona en muchos casos, no funciona en todos y debido a la forma en que React programa las actualizaciones internamente, es difícil predecir cuándo puedes usar la versión síncrona. -We will deprecate and remove the sync version in the future. +Deprecaremos y eliminaremos la versión síncrona en el futuro. -#### Parameters {/*parameters*/} +#### Parámetros {/*parameters*/} -* `async actFn`: An async function wrapping renders or interactions for components being tested. Any updates triggered within the `actFn`, are added to an internal act queue, which are then flushed together to process and apply any changes to the DOM. Since it is async, React will also run any code that crosses an async boundary, and flush any updates scheduled. +* `async actFn`: Una función asíncrona que envuelve renderizados o interacciones para los componentes que se están probando. Cualquier actualización disparada dentro de `actFn` se agrega a una cola interna de act, que luego se procesan juntas para aplicar cualquier cambio al DOM. Dado que es asíncrona, React también ejecutará cualquier código que cruce un límite asíncrono y vaciará cualquier actualización programada. -#### Returns {/*returns*/} +#### Retorno {/*returns*/} -`act` does not return anything. +`act` no devuelve nada. -## Usage {/*usage*/} +## Uso {/*usage*/} -When testing a component, you can use `act` to make assertions about its output. +Al probar un componente, puedes usar `act` para realizar aserciones sobre su salida. -For example, let’s say we have this `Counter` component, the usage examples below show how to test it: +Por ejemplo, supongamos que tenemos este componente `Counter`, los ejemplos de uso a continuación muestran cómo probarlo: ```js function Counter() { @@ -84,9 +84,9 @@ function Counter() { } ``` -### Rendering components in tests {/*rendering-components-in-tests*/} +### Renderizar componentes en pruebas {/*rendering-components-in-tests*/} -To test the render output of a component, wrap the render inside `act()`: +Para probar la salida del renderizado de un componente, envuelve el renderizado dentro de `act()`: ```js {10,12} import {act} from 'react'; @@ -97,7 +97,7 @@ it('can render and update a counter', async () => { container = document.createElement('div'); document.body.appendChild(container); - // ✅ Render the component inside act(). + // ✅ Renderiza el componente dentro de act(). await act(() => { ReactDOMClient.createRoot(container).render(); }); @@ -109,13 +109,13 @@ it('can render and update a counter', async () => { }); ``` -Here, we create a container, append it to the document, and render the `Counter` component inside `act()`. This ensures that the component is rendered and its effects are applied before making assertions. +Aquí, creamos un contenedor, lo añadimos al documento y renderizamos el componente `Counter` dentro de `act()`. Esto asegura que el componente se renderice y sus efectos se apliquen antes de realizar las aserciones. -Using `act` ensures that all updates have been applied before we make assertions. +Usar `act` asegura que todas las actualizaciones se hayan aplicado antes de realizar las aserciones. -### Dispatching events in tests {/*dispatching-events-in-tests*/} +### Despachar eventos en pruebas {/*dispatching-events-in-tests*/} -To test events, wrap the event dispatch inside `act()`: +Para probar eventos, envuelve el despacho del evento dentro de `act()`: ```js {14,16} import {act} from 'react'; @@ -130,7 +130,7 @@ it.only('can render and update a counter', async () => { ReactDOMClient.createRoot(container).render(); }); - // ✅ Dispatch the event inside act(). + // ✅ Despacha el evento dentro de act(). await act(async () => { button.dispatchEvent(new MouseEvent('click', { bubbles: true })); }); @@ -142,21 +142,21 @@ it.only('can render and update a counter', async () => { }); ``` -Here, we render the component with `act`, and then dispatch the event inside another `act()`. This ensures that all updates from the event are applied before making assertions. +Aquí, renderizamos el componente con `act` y luego despachamos el evento dentro de otro `act()`. Esto asegura que todas las actualizaciones del evento se apliquen antes de realizar las aserciones. -Don’t forget that dispatching DOM events only works when the DOM container is added to the document. You can use a library like [React Testing Library](https://testing-library.com/docs/react-testing-library/intro) to reduce the boilerplate code. +No olvides que despachar eventos del DOM solo funciona cuando el contenedor del DOM se ha añadido al documento. Puedes usar una biblioteca como [React Testing Library](https://testing-library.com/docs/react-testing-library/intro) para reducir el código repetitivo. -## Troubleshooting {/*troubleshooting*/} +## Solución de problemas {/*troubleshooting*/} -### I'm getting an error: "The current testing environment is not configured to support act"(...)" {/*error-the-current-testing-environment-is-not-configured-to-support-act*/} +### Recibo un error: "The current testing environment is not configured to support act"(...)" {/*error-the-current-testing-environment-is-not-configured-to-support-act*/} -Using `act` requires setting `global.IS_REACT_ACT_ENVIRONMENT=true` in your test environment. This is to ensure that `act` is only used in the correct environment. +Usar `act` requiere configurar `global.IS_REACT_ACT_ENVIRONMENT=true` en tu entorno de pruebas. Esto es para asegurar que `act` solo se use en el entorno correcto. -If you don't set the global, you will see an error like this: +Si no configuras la variable global, verás un error como este: @@ -164,7 +164,7 @@ Warning: The current testing environment is not configured to support act(...) -To fix, add this to your global setup file for React tests: +Para solucionarlo, añade esto a tu archivo de configuración global para las pruebas de React: ```js global.IS_REACT_ACT_ENVIRONMENT=true @@ -172,6 +172,6 @@ global.IS_REACT_ACT_ENVIRONMENT=true -In testing frameworks like [React Testing Library](https://testing-library.com/docs/react-testing-library/intro), `IS_REACT_ACT_ENVIRONMENT` is already set for you. +En frameworks de pruebas como [React Testing Library](https://testing-library.com/docs/react-testing-library/intro), `IS_REACT_ACT_ENVIRONMENT` ya está configurado por ti.