Course Content
React Mastery
React Mastery
Conditional Rendering
Conditional rendering allows us to show or hide elements based on certain conditions dynamically, enhancing the flexibility of React components. This section will explore two standard conditional rendering techniques: the &&
operator and the ternary operator.
Conditional Rendering with the && Operator
Syntax
The &&
operator in React is used for conditional rendering and works similarly to an if
statement in JavaScript. It enables us to render elements based on specific conditions.
This technique is often employed when we want to display an element only if a particular condition evaluates to true.
Example
Let's take an example where we want to notify students who have passed an exam. If a student's score exceeds 60 points, we'll display a success message with their name and score.
The Notification
component conditionally renders a paragraph <p>
element based on the mark
prop value.
Full app code
Emily's score isn't shown because it's less than 60pts
.
Conditional Rendering with the Ternary Operator
Syntax
Conditional rendering using the ternary operator (? ... : ...
) is another powerful technique. It provides a concise way to render elements based on conditions.
This approach is suitable when choosing between two distinct elements based on a condition.
Example
Consider a scenario where we want to greet users differently based on their logged-in. The Greeting
component demonstrates conditional rendering with the ternary operator.
In this example, the Greeting
component greets users differently based on the loggedIn
prop value.
Full app code
Note
While both techniques achieve conditional rendering, it's essential to understand their differences. The
&&
operator is ideal when you want to render an element only when a specific condition is met. In contrast, the ternary operator is suitable for cases where you need to choose between two distinct elements based on a condition.
Thanks for your feedback!