diff --git a/beta/src/pages/learn/conditional-rendering.md b/beta/src/pages/learn/conditional-rendering.md index cfc6f19be..8cf85f059 100644 --- a/beta/src/pages/learn/conditional-rendering.md +++ b/beta/src/pages/learn/conditional-rendering.md @@ -1,24 +1,24 @@ --- -title: Conditional Rendering +title: Renderizado Condicional --- -Your components will often need to display different things depending on different conditions. In React, you can conditionally render JSX using JavaScript syntax like `if` statements, `&&`, and `? :` operators. +Tus componentes a menudo necesitarán mostrar diferentes cosas dependiendo de diferentes condiciones. En React, puedes renderizar JSX de forma condicional utilizando la sintaxis de JavaScript como las declaraciones `if`, `&&` y los operadores `? :`. -* How to return different JSX depending on a condition -* How to conditionally include or exclude a piece of JSX -* Common conditional syntax shortcuts you’ll encounter in React codebases +* Cómo devolver distinto JSX dependiendo de una condición +* Cómo incluir o excluir condicionalmente un fragmento de JSX +* Atajos de sintaxis condicional comunes que encontrarás en las bases de código de React -## Conditionally returning JSX {/*conditionally-returning-jsx*/} +## Devolución condicional de JSX {/*conditionally-returning-jsx*/} -Let’s say you have a `PackingList` component rendering several `Item`s, which can be marked as packed or not: +Supongamos que tienes un componente `PackingList` que muestra varios `Items`, que pueden ser marcados como empaquetados o no: @@ -52,9 +52,9 @@ export default function PackingList() { -Notice that some of the `Item` components have their `isPacked` prop set to `true` instead of `false`. You want to add a checkmark (✔) to packed items if `isPacked={true}`. +Observa que algunos de los componentes `Item` tienen su prop `isPacked` asignada a `true` en lugar de `false`. Se desea añadir una marca de verificación (✔) a los elementos empaquetados si `isPacked={true}`. -You can write this as an [`if`/`else` statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else) like so: +Puedes escribir esto como una declaración [`if`/`else`](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Statements/if...else) así: ```js if (isPacked) { @@ -63,7 +63,7 @@ if (isPacked) { return
  • {name}
  • ; ``` -If the `isPacked` prop is `true`, this code **returns a different JSX tree**. With this change, some of the items get a checkmark at the end: +Si la prop `isPacked` es `true`, este código **devuelve un árbol JSX diferente**. Con este cambio, algunos de los elementos obtienen una marca de verificación al final: @@ -100,13 +100,13 @@ export default function PackingList() { -Try editing what gets returned in either case, and see how the result changes! +Prueba a editar lo que se devuelve en cualquiera de los dos casos y observa cómo cambia el resultado. -Notice how you're creating branching logic with JavaScript's `if` and `return` statements. In React, control flow (like conditions) is handled by JavaScript. +Observa cómo estás creando una lógica de ramificación con las sentencias `if` y `return` de JavaScript. En React, el flujo de control (como las condiciones) es manejado por JavaScript. -### Conditionally returning nothing with `null` {/*conditionally-returning-nothing-with-null*/} +### Devolución de nada con `null` {/*conditionally-returning-nothing-with-null*/} -In some situations, you won't want to render anything at all. For example, say you don't want to show packed items at all. A component must return something. In this case, you can return `null`: +En algunas situaciones, no querrás mostrar nada en absoluto. Por ejemplo, digamos que no quieres mostrar elementos empaquetados en absoluto. Un componente debe devolver algo. En este caso, puedes devolver `null`: ```js if (isPacked) { @@ -115,7 +115,7 @@ if (isPacked) { return
  • {name}
  • ; ``` -If `isPacked` is true, the component will return nothing, `null`. Otherwise, it will return JSX to render. +Si `isPacked` es verdadero, el componente no devolverá nada, `null`. En caso contrario, devolverá JSX para ser renderizado. @@ -152,23 +152,23 @@ export default function PackingList() { -In practice, returning `null` from a component isn't common because it might surprise a developer trying to render it. More often, you would conditionally include or exclude the component in the parent component's JSX. Here's how to do that! +En la práctica, devolver `null` en un componente no es común porque podría sorprender a un desarrollador que intente renderizarlo. Lo más frecuente es incluir o excluir condicionalmente el componente en el JSX del componente padre. Aquí se explica cómo hacerlo. -## Conditionally including JSX {/*conditionally-including-jsx*/} +## Exclusión condicional de JSX {/*conditionally-including-jsx*/} -In the previous example, you controlled which (if any!) JSX tree would be returned by the component. You may already have noticed some duplication in the render output: +En el ejemplo anterior, controlabas qué árbol JSX (si es que había alguno) era devuelto por el componente. Es posible que ya hayas notado alguna duplicación en la salida de la renderización: ```js
  • {name} ✔
  • ``` -is very similar to +es muy similar a ```js
  • {name}
  • ``` -Both of the conditional branches return `
  • ...
  • `: +Ambas ramas condicionales devuelven `
  • ...
  • `: ```js if (isPacked) { @@ -177,13 +177,13 @@ if (isPacked) { return
  • {name}
  • ; ``` -While this duplication isn't harmful, it could make your code harder to maintain. What if you want to change the `className`? You'd have to do it in two places in your code! In such a situation, you could conditionally include a little JSX to make your code more [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself). +Aunque esta duplicación no es perjudicial, podría hacer que tu código sea más difícil de mantener. ¿Qué pasa si quieres cambiar el `className`? ¡Tendrías que hacerlo en dos lugares en tu código! En tal situación, podrías incluir condicionalmente un poco de JSX para hacer tu código más [DRY](https://es.wikipedia.org/wiki/No_te_repitas). -### Conditional (ternary) operator (`? :`) {/*conditional-ternary-operator--*/} +### Operador condicional (ternario) (`? :`) {/*conditional-ternary-operator--*/} -JavaScript has a compact syntax for writing a conditional expression -- the [conditional operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) or "ternary operator." +JavaScript tiene una sintaxis compacta para escribir una expresión condicional -- el [operador condicional](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) u "operador ternario". -Instead of this: +En lugar de esto: ```js if (isPacked) { @@ -192,7 +192,7 @@ if (isPacked) { return
  • {name}
  • ; ``` -You can write this: +Puedes escribir esto: ```js return ( @@ -202,15 +202,15 @@ return ( ); ``` -You can read it as *"if `isPacked` is true, then (`?`) render `name + ' ✔'`, otherwise (`:`) render `name`."*) +Puedes leerlo como *"si `isPacked` es verdadero, entonces (`?`) renderiza `name + ' ✔'`, de lo contrario (`:`) renderiza `name`"*) -If you're coming from an object-oriented programming background, you might assume that the two examples above are subtly different because one of them may create two different "instances" of `
  • `. But JSX elements aren't "instances" because they don't hold any internal state and aren't real DOM nodes. They're lightweight descriptions, like blueprints. So these two examples, in fact, *are* completely equivalent. [Preserving and Resetting State](/learn/preserving-and-resetting-state) goes into detail about how this works. +Si vienes de un entorno de programación orientada a objetos, podrías asumir que los dos ejemplos anteriores son sutilmente diferentes porque uno de ellos puede crear dos "instancias" diferentes de `
  • `. Pero los elementos JSX no son "instancias" porque no contienen ningún estado interno y no son nodos reales del DOM. Son descripciones ligeras, como los planos. Así que estos dos ejemplos, de hecho, *son* completamente equivalentes. En [Conservación y Restablecimiento del estado](/learn/preserving-and-resetting-state) se explica en detalle cómo funciona esto. -Now let's say you want to wrap the completed item's text into another HTML tag, like `` to strike it out. You can add even more newlines and parentheses so that it's easier to nest more JSX each of the cases: +Ahora digamos que quieres envolver el texto del elemento completado en otra etiqueta HTML, como `` para tacharlo. Puedes añadir aún más líneas nuevas y paréntesis para que sea más fácil anidar más JSX en cada uno de los casos: @@ -254,11 +254,11 @@ export default function PackingList() { -This style works well for simple conditions, but use it in moderation. If your components get messy with too much nested conditional markup, consider extracting child components to clean things up. In React, markup is a part of your code, so you can use tools like variables and functions to tidy up complex expressions. +Este estilo funciona bien para condiciones simples, pero utilízalo con moderación. Si tus componentes se desordenan con demasiado marcado condicional anidado, considera la posibilidad de extraer componentes hijos para limpiar las cosas. En React, el marcado es una parte de tu código, por lo que puedes utilizar herramientas como variables y funciones para ordenar las expresiones complejas. -### Logical AND operator (`&&`) {/*logical-and-operator-*/} +### Operador lógico AND (`&&`) {/*logical-and-operator-*/} -Another common shortcut you'll encounter is the [JavaScript logical AND (`&&`) operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND#:~:text=The%20logical%20AND%20(%20%26%26%20)%20operator,it%20returns%20a%20Boolean%20value.). Inside React components, it often comes up when you want to render some JSX when the condition is true, **or render nothing otherwise.** With `&&`, you could conditionally render the checkmark only if `isPacked` is `true`: +Otro atajo común que encontrarás es el [operador lógico AND (`&&`) de JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND#:~:text=The%20logical%20AND%20(%20%26%20)%20operator,it%20returns%20a%20Boolean%20value.). Dentro de los componentes de React, a menudo surge cuando quieres renderizar algún JSX cuando la condición es verdadera, **o no renderizar nada en caso contrario.** Con `&&`, podrías renderizar condicionalmente la marca de verificación sólo si `isPacked` es `true`: ```js return ( @@ -268,9 +268,9 @@ return ( ); ``` -You can read this as *“if `isPacked`, then (`&&`) render the checkmark, otherwise, render nothing.”* +Puedes leer esto como *"si `isPacked`, entonces (`&&`) renderiza la marca de verificación, si no, no renderiza nada."* -Here it is in action: +Aquí está en acción: @@ -308,30 +308,30 @@ export default function PackingList() { -A [JavaScript && expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND) returns the value of its right side (in our case, the checkmark) if the left side (our condition) is `true`. But if the condition is `false`, the whole expression becomes `false`. React considers `false` as a "hole" in the JSX tree, just like `null` or `undefined`, and doesn't render anything in its place. +Una [expresión JavaScript &&](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND) devuelve el valor de su lado derecho (en nuestro caso, la marca de verificación) si el lado izquierdo (nuestra condición) es `true`. Pero si la condición es `false`, toda la expresión se convierte en `false`. React considera `false` como un "agujero" en el árbol JSX, al igual que `null` o `undefined`, y no renderiza nada en su lugar. -**Don't put numbers on the left side of `&&`.** +**No pongas números a la izquierda de `&&`.** -To test the condition, JavaScript converts the left side to a boolean automatically. However, if the left side is `0`, then the whole expression gets that value (`0`), and React will happily render `0` rather than nothing. +Para comprobar la condición, JavaScript convierte el lado izquierdo en un booleano automáticamente. Sin embargo, si el lado izquierdo es `0`, entonces toda la expresión obtiene ese valor (`0`), y React representará felizmente `0` en lugar de nada. -For example, a common mistake is to write code like `messageCount &&

    New messages

    `. It's easy to assume that it renders nothing when `messageCount` is `0`, but it really renders the `0` itself! +Por ejemplo, un error común es escribir código como `messageCount &&

    New messages

    `. Es fácil suponer que no renderiza nada cuando `messageCount` es `0`, pero en realidad renderiza el propio `0`. -To fix it, make the left side a boolean: `messageCount > 0 &&

    New messages

    `. +Para arreglarlo, haz que el lado izquierdo sea un booleano: `messageCount > 0 &&

    New messages

    `.
    -### Conditionally assigning JSX to a variable {/*conditionally-assigning-jsx-to-a-variable*/} +### Asignación condicional de JSX a una variable {/*conditionally-assigning-jsx-to-a-variable*/} -When the shortcuts get in the way of writing plain code, try using an `if` statement and a variable. You can reassign variables defined with [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let), so start by providing the default content you want to display, the name: +Cuando los atajos se interpongan en el camino de la escritura de código simple, prueba a utilizar una sentencia `if` y una variable. Puedes reasignar las variables definidas con [`let`](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Statements/let), así que empieza proporcionando el contenido por defecto que quieres mostrar, el nombre: ```js let itemContent = name; ``` -Use an `if` statement to reassign a JSX expression to `itemContent` if `isPacked` is `true`: +Utiliza una sentencia `if` para reasignar una expresión JSX a `itemContent` si `isPacked` es `true`: ```js if (isPacked) { @@ -339,7 +339,7 @@ if (isPacked) { } ``` -[Curly braces open the "window into JavaScript".](/learn/javascript-in-jsx-with-curly-braces#using-curly-braces-a-window-into-the-javascript-world) Embed the variable with curly braces in the returned JSX tree, nesting the previously calculated expression inside of JSX: +[Las llaves abren la "ventana a JavaScript".](/learn/javascript-in-jsx-with-curly-braces#using-curly-braces-a-window-into-the-javascript-world) Inserta la variable con llaves en el árbol JSX devuelto, anidando la expresión previamente calculada dentro de JSX: ```js
  • @@ -347,7 +347,7 @@ if (isPacked) {
  • ``` -This style is the most verbose, but it's also the most flexible. Here it is in action: +Este estilo es el más verboso, pero también el más flexible. Aquí está en acción: @@ -389,7 +389,7 @@ export default function PackingList() { -Like before, this works not only for text, but for arbitrary JSX too: +Como antes, esto funciona no sólo para el texto, sino también para JSX arbitrario: @@ -435,16 +435,16 @@ export default function PackingList() { -If you're not familiar with JavaScript, this variety of styles might seem overwhelming at first. However, learning them will help you read and write any JavaScript code -- and not just React components! Pick the one you prefer for a start, and then consult this reference again if you forget how the other ones work. +Si no estás familiarizado con JavaScript, esta variedad de estilos puede parecer abrumadora al principio. Sin embargo, aprenderlos te ayudará a leer y escribir cualquier código JavaScript -- ¡y no sólo los componentes de React! Escoge el que prefieras para empezar, y luego vuelve a consultar esta referencia si olvidas cómo funcionan los demás. -* In React, you control branching logic with JavaScript. -* You can return a JSX expression conditionally with an `if` statement. -* You can conditionally save some JSX to a variable and then include it inside other JSX by using the curly braces. -* In JSX, `{cond ? : }` means *"if `cond`, render ``, otherwise ``"*. -* In JSX, `{cond && }` means *"if `cond`, render ``, otherwise nothing"*. -* The shortcuts are common, but you don't have to use them if you prefer plain `if`. +* En React, se controla la lógica de ramificación con JavaScript. +* Puedes devolver una expresión JSX condicionalmente con una sentencia `if`. +* Puedes guardar condicionalmente algún JSX en una variable y luego incluirlo dentro de otro JSX usando las llaves. +* En JSX, `{cond ? : }` significa *"si `cond`, renderiza ``, si no ``"*. +* En JSX, `{cond && }` significa *"si `cond`, renderiza ``, si no, nada"*. +* Los atajos son comunes, pero no tienes que usarlos si prefieres el simple `if`. @@ -452,9 +452,9 @@ If you're not familiar with JavaScript, this variety of styles might seem overwh -### Show an icon for incomplete items with `? :` {/*show-an-icon-for-incomplete-items-with--*/} +### Mostrar un icono para los elementos incompletos con `? :` {/*show-an-icon-for-incomplete-items-with--*/} -Use the conditional operator (`cond ? a : b`) to render a ❌ if `isPacked` isn’t `true`. +Utiliza el operador condicional (`cond ? a : b`) para renderizar un ❌ si `isPacked` no es `true`. @@ -532,15 +532,15 @@ export default function PackingList() { -### Show the item importance with `&&` {/*show-the-item-importance-with-*/} +### Mostrar la importancia del elemento con `&&` {/*show-the-item-importance-with-*/} -In this example, each `Item` receives a numerical `importance` prop. Use the `&&` operator to render "_(Importance: X)_" in italics, but only for items that have non-zero importance. Your item list should end up looking like this: +En este ejemplo, cada "elemento" recibe una "importancia" numérica. Utiliza el operador `&&` para mostrar "_(Importance: X)_" en cursiva, pero sólo para los elementos que tienen una importancia distinta de cero. Tu lista de elementos debería tener este aspecto: * Space suit _(Importance: 9)_ * Helmet with a golden leaf * Photo of Tam _(Importance: 6)_ -Don't forget to add a space between the two labels! +¡No olvides añadir un espacio entre las dos etiquetas! @@ -580,7 +580,7 @@ export default function PackingList() { -This should do the trick: +Esto debería servir: @@ -622,15 +622,15 @@ export default function PackingList() { -Note that you must write `importance > 0 && ...` rather than `importance && ...` so that if the `importance` is `0`, `0` isn't rendered as the result! +Ten en cuenta que debes escribir `importance > 0 && ...` en lugar de `importance && ...` para que si `importance` es `0`, ¡no se muestre `0` como resultado! -In this solution, two separate conditions are used to insert a space between then name and the importance label. Alternatively, you could use a fragment with a leading space: `importance > 0 && <> ...` or add a space immediately inside the ``: `importance > 0 && ...`. +En esta solución, se utilizan dos condiciones distintas para insertar un espacio entre el nombre y la etiqueta de importancia. Como alternativa, puedes utilizar un fragmento con un espacio inicial: `importance > 0 && <> ...` o añadir un espacio inmediatamente dentro del ``: `importance > 0 && ...`. -### Refactor a series of `? :` to `if` and variables {/*refactor-a-series-of---to-if-and-variables*/} +### Refactorizar una serie de `? :` a `if` y variables {/*refactor-a-series-of---to-if-and-variables*/} -This `Drink` component uses a series of `? :` conditions to show different information depending on whether the `name` prop is `"tea"` or `"coffee"`. The problem is that the information about each drink is spread across multiple conditions. Refactor this code to use a single `if` statement instead of three `? :` conditions. +Este componente `Drink` utiliza una serie de condiciones `? :` para mostrar diferente información dependiendo de si la prop `name` es `té` o `café`. El problema es que la información sobre cada bebida está repartida entre varias condiciones. Refactoriza este código para utilizar una única sentencia `if` en lugar de tres condiciones `? :`. @@ -663,11 +663,11 @@ export default function DrinkList() { -Once you've refactored the code to use `if`, do you have further ideas on how to simplify it? +Una vez refactorizado el código para utilizar `if`, ¿tienes más ideas sobre cómo simplificarlo? -There are multiple ways you could go about this, but here is one starting point: +Hay muchas maneras de hacerlo, pero este es un punto de partida: @@ -710,9 +710,9 @@ export default function DrinkList() { -Here the information about each drink is grouped together instead of being spread across multiple conditions. This makes it easier to add more drinks in the future. +Aquí la información sobre cada bebida se agrupa en lugar de estar repartida en múltiples condiciones. Esto facilita la adición de más bebidas en el futuro. -Another solution would be to remove the condition altogether by moving the information into objects: +Otra solución sería eliminar la condición por completo moviendo la información a los objetos: @@ -761,4 +761,4 @@ export default function DrinkList() { - \ No newline at end of file +