You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/docs/conditional-rendering.md
+33-39Lines changed: 33 additions & 39 deletions
Original file line number
Diff line number
Diff line change
@@ -1,18 +1,18 @@
1
1
---
2
2
id: conditional-rendering
3
-
title: Conditional Rendering
3
+
title: Renderizado condicional
4
4
permalink: docs/conditional-rendering.html
5
5
prev: handling-events.html
6
6
next: lists-and-keys.html
7
7
redirect_from:
8
8
- "tips/false-in-jsx.html"
9
9
---
10
10
11
-
In React, you can create distinct components that encapsulate behavior you need. Then, you can render only some of them, depending on the state of your application.
11
+
En React, puedes crear distintos componentes que encapsulan el comportamiento que necesitas. Entonces, puedes renderizar solamente algunos de ellos, dependiendo del estado de tu aplicación.
12
12
13
-
Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like [`if`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else)or the [conditional operator](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator)to create elements representing the current state, and let React update the UI to match them.
13
+
El renderizado condicional en React funciona de la misma forma que lo hacen las condiciones en JavaScript. Usa operadores de JavaScript como [`if`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else)o el [operador condicional](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Operadores/Conditional_Operator)para crear elementos representando el estado actual, y deja que React actualice la UI para emparejarlos.
14
14
15
-
Consider these two components:
15
+
Considera estos dos componentes:
16
16
17
17
```js
18
18
functionUserGreeting(props) {
@@ -24,7 +24,7 @@ function GuestGreeting(props) {
24
24
}
25
25
```
26
26
27
-
We'll create a `Greeting`component that displays either of these components depending on whether a user is logged in:
27
+
Vamos a crear un componente `Greeting`que muestra cualquiera de estos componentes dependiendo si el usuario ha iniciado sesión:
28
28
29
29
```javascript{3-7,11,12}
30
30
function Greeting(props) {
@@ -36,21 +36,21 @@ function Greeting(props) {
36
36
}
37
37
38
38
ReactDOM.render(
39
-
// Try changing to isLoggedIn={true}:
39
+
// Intentar cambiando isLoggedIn={true}:
40
40
<Greeting isLoggedIn={false} />,
41
41
document.getElementById('root')
42
42
);
43
43
```
44
44
45
-
[**Try it on CodePen**](https://codepen.io/gaearon/pen/ZpVxNq?editors=0011)
45
+
[**Pruébalo en CodePen**](https://codepen.io/gaearon/pen/ZpVxNq?editors=0011)
46
46
47
-
This example renders a different greeting depending on the value of `isLoggedIn` prop.
47
+
Este ejemplo renderiza un saludo diferente según el valor de la prop `isLoggedIn`.
48
48
49
-
### Element Variables
49
+
### Variables de elementos
50
50
51
-
You can use variables to store elements. This can help you conditionally render a part of the component while the rest of the output doesn't change.
51
+
Puedes usar variables para almacenar elementos. Esto puede ayudarte para renderizar condicionalmente una parte del componente mientras el resto del resultado no cambia.
52
52
53
-
Consider these two new components representing Logout and Login buttons:
53
+
Considera estos dos componentes nuevos que representan botones de cierre e inicio de sesión:
54
54
55
55
```js
56
56
functionLoginButton(props) {
@@ -70,9 +70,9 @@ function LogoutButton(props) {
70
70
}
71
71
```
72
72
73
-
In the example below, we will create a [stateful component](/docs/state-and-lifecycle.html#adding-local-state-to-a-class)called`LoginControl`.
73
+
En el siguiente ejemplo, crearemos un [componente con estado](/docs/state-and-lifecycle.html#adding-local-state-to-a-class)llamado`LoginControl`.
74
74
75
-
It will render either `<LoginButton />`or`<LogoutButton />`depending on its current state. It will also render a`<Greeting />`from the previous example:
75
+
El componente va a renderizar `<LoginButton />`o`<LogoutButton />`dependiendo de su estado actual. También va a renderizar un`<Greeting />`del ejemplo anterior:
76
76
77
77
```javascript{20-25,29,30}
78
78
class LoginControl extends React.Component {
@@ -82,25 +82,20 @@ class LoginControl extends React.Component {
[**Try it on CodePen**](https://codepen.io/gaearon/pen/QKzAgB?editors=0010)
114
+
[**Pruébalo en CodePen**](https://codepen.io/gaearon/pen/QKzAgB?editors=0010)
120
115
121
-
While declaring a variable and using an `if`statement is a fine way to conditionally render a component, sometimes you might want to use a shorter syntax. There are a few ways to inline conditions in JSX, explained below.
116
+
Si bien declarar una variable y usar una sentencia `if`es una buena forma de renderizar condicionalmente un componente, a veces podrías querer usar una sintaxis más corta. Hay algunas formas de hacer condiciones en una línea en JSX, explicadas a continuación.
122
117
123
-
### Inline If with Logical && Operator
118
+
### If en una línea con operador lógico &&
124
119
125
-
You may [embed any expressions in JSX](/docs/introducing-jsx.html#embedding-expressions-in-jsx)by wrapping them in curly braces. This includes the JavaScript logical`&&`operator. It can be handy for conditionally including an element:
120
+
Puedes [embeber cualquier expresión en JSX](/docs/introducing-jsx.html#embedding-expressions-in-jsx)envolviéndola en llaves. Esto incluye al operador lógico`&&`de JavaScript. Puede ser útil para incluir condicionalmente un elemento:
126
121
127
122
```js{6-10}
128
123
function Mailbox(props) {
@@ -146,17 +141,17 @@ ReactDOM.render(
146
141
);
147
142
```
148
143
149
-
[**Try it on CodePen**](https://codepen.io/gaearon/pen/ozJddz?editors=0010)
144
+
[**Pruébalo en CodePen**](https://codepen.io/gaearon/pen/ozJddz?editors=0010)
150
145
151
-
It works because in JavaScript, `true && expression` always evaluates to `expression`, and`false && expression` always evaluates to`false`.
146
+
Esto funciona porque en JavaScript, `true && expresión` siempre evalúa a `expresión`, y`false && expresión` siempre evalúa a`false`.
152
147
153
-
Therefore, if the condition is`true`, the element right after `&&`will appear in the output. If it is `false`, React will ignore and skip it.
148
+
Por eso, si la condición es`true`, el elemento justo después de `&&`aparecerá en el resultado. Si es `false`, React lo ignorará.
154
149
155
-
### Inline If-Else with Conditional Operator
150
+
### If-Else en una línea con operador condicional
156
151
157
-
Another method for conditionally rendering elements inline is to use the JavaScript conditional operator [`condition ? true : false`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Conditional_Operator).
152
+
Otro método para el renderizado condicional de elementos en una línea es usar el operador condicional [`condición ? true : false`](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Operadores/Conditional_Operator) de JavaScript.
158
153
159
-
In the example below, we use it to conditionally render a small block of text.
154
+
En el siguiente ejemplo, lo usaremos para renderizar de forma condicional un pequeño bloque de texto.
160
155
161
156
```javascript{5}
162
157
render() {
@@ -169,7 +164,7 @@ render() {
169
164
}
170
165
```
171
166
172
-
It can also be used for larger expressions although it is less obvious what's going on:
167
+
También puede usarse para expresiones más grandes, aunque es menos obvio lo que está pasando:
173
168
174
169
```js{5,7,9}
175
170
render() {
@@ -179,27 +174,26 @@ render() {
179
174
{isLoggedIn ? (
180
175
<LogoutButton onClick={this.handleLogoutClick} />
181
176
) : (
182
-
<LoginButton onClick={this.handleLoginClick} />
177
+
<LoginButton onClick={this.handleLoginClick} />
183
178
)}
184
179
</div>
185
180
);
186
181
}
187
182
```
188
183
189
-
Just like in JavaScript, it is up to you to choose an appropriate style based on what you and your team consider more readable. Also remember that whenever conditions become too complex, it might be a good time to [extract a component](/docs/components-and-props.html#extracting-components).
184
+
Al igual que en JavaScript, depende de ti elegir un estilo apropiado en base a lo que tu y tu equipo consideran más legible. Recuerda también que cuando las condiciones se vuelven demasiado complejas, puede ser un buen momento para [extraer un componente](/docs/components-and-props.html#extracting-components).
190
185
191
-
### Preventing Component from Rendering
186
+
### Evitar que el componente se renderice
192
187
193
-
In rare cases you might want a component to hide itself even though it was rendered by another component. To do this return`null`instead of its render output.
188
+
En casos excepcionales, es posible que desees que un componente se oculte a sí mismo aunque haya sido renderizado por otro componente. Para hacer esto, devuelve`null`en lugar del resultado de renderizado.
194
189
195
-
In the example below, the`<WarningBanner />`is rendered depending on the value of the prop called`warn`. If the value of the prop is`false`, then the component does not render:
190
+
En el siguiente ejemplo, el`<WarningBanner />`se renderiza dependiendo del valor de la prop llamada`warn`. Si el valor de la prop es`false`, entonces el componente no se renderiza:
196
191
197
192
```javascript{2-4,29}
198
193
function WarningBanner(props) {
199
194
if (!props.warn) {
200
195
return null;
201
196
}
202
-
203
197
return (
204
198
<div className="warning">
205
199
Warning!
@@ -213,13 +207,11 @@ class Page extends React.Component {
[**Try it on CodePen**](https://codepen.io/gaearon/pen/Xjoqwm?editors=0010)
233
+
[**Pruébalo en CodePen**](https://codepen.io/gaearon/pen/Xjoqwm?editors=0010)
234
+
235
+
El devolver `null` desde el método `render` de un componente no influye en la activación de los métodos del ciclo de vida del componente. Por ejemplo `componentDidUpdate` seguirá siendo llamado.
236
+
242
237
243
-
Returning `null` from a component's `render` method does not affect the firing of the component's lifecycle methods. For instance `componentDidUpdate` will still be called.
0 commit comments