After this lesson you will be able to:
In React, you can create distinct components that encapsulate the behavior you need. Then, you can render only some of them, depending on the state of your application.
Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like if or the conditional operator to create elements representing the current state, and let React update the UI to match them.
Example:
While 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. One way to go about this is using ternary operator: condition ? true : false
.
Let's keep working within our small project and our next step is to slightly update our movies
array in the state of <DynamicMoviesList />
component:
Reprise du projet my-new-app
et modification des datas pour ajouter les champs hasOscars
et IMDbRating
aux objects movies :
Nothing's still changed in our app, we still can see the same result. So let's make some changes in our <ImprovedCard />
component. We can implement inline ternary operator for more straightforward logic:
Nous allons maintenant, grâce à l'opérateur ternaire, afficher si oui ou non un film a reçu un oscar grâce à la nouvelle donnée hasOscars
Plus simple que de définir une fonction utilitaire :
appelée par:
On remarque aussi la présence des {}
autour :
On oublie pas non plus que la valeur retournée doit être dans une balise englobante :
Even simpler logic
Let's use a more outstanding approach that has better use of JS grammar. You may embed any expressions in JSX by wrapping them in curly braces. This includes the JavaScript logical &&
operator. Let's update code in our ImprovedCard.js:
Opérateurs booléens: &&
, ||
It works because in JavaScript, true && expression always evaluates to expression, and false && expression always evaluates to false.
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.
Si plus complexe qu'un simple if/else
=> recours aux variables avant le return
If the conditional rendering logic is a more complex, which is not in our case but we will use this example to demonstrate the approach, it is better to extract condition outside JSX:
The other way of displaying the movies in the <DynamicMoviesList />
component could be something like this:
Nous allons maintenant filtrer la liste des films, en fonction de s'ils ont ou non remportés un oscar :
Nous affichons maintenant une liste de films, filtrés avec la valeur de l'état this.props.showOscarAwarded
. La liste filtrée est "calculée" à chaque render()
Nous ré-initialisons la liste de films à chaque appel à this.toggleMovies
Notons aussi l'utilisation de l'opérateur ternaire ligne 41.
Take a look of the following example and play around with it:
Ma version : https://codepen.io/abernier/pen/EMaYob?editors=1010
Conditional rendering is one of the most common ways to show/hide components in React apps. When developing your applications you will find situations where you want to display specific components depending on some variables, so be sure to understand how to implement the conditional rendering.