PresentationInteractive, narrated presentation of the section content.
Code ExampleInteractive coding exercise.
No problems found.
ContentDetailed description of the section content.
Imagine you're building an app that greets users based on their age. You want to show a silly message if the user is a kid. You want to keep things a bit more formal if they're an adult. Here's how you could use an if...else statement to achieve this:
import React from 'react';
function QuirkyAgeGreeter(props) {
const { age } = props;
if (age < 18) {
return (
<div>
<h1>Hey there, little squirt!</h1>
<p>Welcome to the wacky world of React!</p>
</div>
);
} else {
return (
<div>
<h1>Greetings, esteemed individual.</h1>
<p>We're delighted to have you in our quirky React application.</p>
</div>
);
}
}In this example, we check if the age prop is less than 18. If it is, we render a silly greeting for kids. If not, we will render a more formal greeting for adults.
🤔 But what if you would like to use several different conditions in a more complex component? This approach would get really problematic with each if-else branch. Luckily, in React, we can use logical chaining, ternary operators or null-coalescing operator directly in the JSX. Let's take a look!
Prerequisites
First, let's check out how React handles and renders different truthy and falsy values. Check out the example below:
From the example above, we can clearly see that react does not render almost any of the truthy or falsy values. The only falsy value rendered is 0 and NaN. With arrays, the content of arrays is rendered. ⚠️ Objects cannot be rendered and you will receive an error when trying to render an object value. With this knowledge in mind we can explore alternative approaches to conditional rendering.
Alternative ways of defining React conditionals
1. Null Coalescing Operator
In React, the null coalescing operator (??) is especially useful when you want to set default values for props or state that might be null or undefined. It helps ensure that your components render correctly even if the data isn't available yet or if something went wrong somewhere else in your code.
Let's consider a simple React component that displays a user's profile information, but sometimes the user's name or bio might not be available. We can use the null coalescing operator to handle these cases gracefully.
Here's an example:
import React from 'react';
function UserProfile({ userName, userBio }) {
// Set default values if userName or userBio are null or undefined
const displayName = userName ?? 'Anonymous';
const displayBio = userBio ?? 'No bio available';
return (
<div>
<h1>Welcome, {displayName}!</h1>
<p>{displayBio}</p>
</div>
);
}
// Usage
function App() {
// Example: userName is undefined, userBio is null
return <UserProfile userName={undefined} userBio={null} />;
}In this example:
UserProfile is a component that takes userName and userBio as props.
We use the null coalescing operator ?? to set displayName to 'Anonymous' if userName is null or undefined.
Similarly, displayBio is set to 'No bio available' if userBio is null or undefined.
When the component is used in the App component, both userName and userBio are not provided with meaningful values (userName is undefined and userBio is null), so the default values are displayed.
This approach ensures that your component always has valid data to display and avoids any potential issues or crashes that might occur if it tried to render null or undefined values.
2. Ternary Operator
The ternary operator is another useful tool in JavaScript and React for handling conditional logic in a concise way. It's often used to choose between two values based on a condition, essentially creating an if-else branching. The syntax for the ternary operator is <strong>condition ? valueIfTrue : valueIfFalse</strong>.
Let's use the same React component from before, but this time we'll use the ternary operator to handle the conditions. This will help illustrate the difference between using the null coalescing operator and the ternary operator.
Here's how you can rewrite the UserProfile component using the ternary operator:
import React from 'react';
function UserProfile({ userName, userBio, userAge }) {
return (
<div>
<h1>
{ userAge < 18 ? 'Yo!': 'Welcome' },
{
userName ?
userName :
<div>Error: You need to provide the user name</div>
}!
</h1>
<p>{userBio ? userBio : 'No bio available' }</p>
</div>
);
}
// Usage
function App() {
// Example: userName is undefined, userBio is null
return <UserProfile userName={undefined} userBio={null} userAge={6} />;
}Explanation
In this example:
We are using the ternary operator to check the values of userName and userBio.
userAge < 18 ? 'Yo!': ‘Welcome’will render age appropriate greeting. If user is under 18 we will displayYo, otherwise plain old boringWelcome.userBio ? userBio : 'No bio available'means:If userBio is truthy (which means it has a value other than null, undefined, false, 0, "", or NaN), then displayBio will be userBio.
- If userBio is falsy (null, undefined, false, 0, "", or NaN), then displayBio will be 'No bio available'.
userName ? userName : (<div>Error: You need to provide the user name</div>)means that if userName is specified we render the first component displaying user info. If userName is not specified (even if bio is), we will render an error message
Key Differences
⚠️ The ternary operator checks if the value is truthy or falsy and uses that to decide which value to use. It's useful for broader conditions beyond just null or undefined.
⚠️ The null coalescing operator (??) specifically checks for null or undefined only, ignoring other falsy values like 0 or false. This makes it particularly useful when you want to differentiate between null/undefined and other "legitimate" falsy values like 0, which you might want to treat as valid.
Using the ternary operator in this way ensures that you handle more cases (all falsy values) compared to the null coalescing operator, which only handles null and undefined. This distinction can be crucial depending on what values are expected and how you want to handle them in your application.
3. Logical Operators
Let's use the same React component example to explain how you can use the logical && (AND) and || (OR) operators to manage conditional rendering. These operators are common in JavaScript for managing flow control and setting default values, and they work slightly differently from the null coalescing and ternary operators.
Using the && and || Operator
The <strong>&&</strong> operator is often used to render components or elements only if all conditions in the expression are true. In the expression <i>A & B & C & D</i> will return the last element <i>D</i> if only all previous conditions <i>A & B & C</i> are truthy. Otherwise, it will return false (i.e. will not render anything). This is useful when we need to check for certain conditions when we want to render a component or value.
The <strong>||</strong> operator is used to return the first truthy value it encounters. If all values are falsy, it returns the last falsy value. In React, it’s particularly useful for setting default values. For example in the expression A || B || C || D will return the first non false value (i.e. existing) out of A, B, C or D. This is useful to provide default values such as in the next example.
Here's how you might use it in our React component:
import React from 'react';
function UserProfile({ userName, userBio, userAge }) {
return (
<div>
<h1>
{ userAge < 18 ? 'Yo!': 'Welcome' },
{ userName || <div>Error: You need to provide the user name</div>}!
</h1>
{ userBio && <p>{userBio}</p> }
</div>
);
}
// Usage
function App() {
// Example: userName is undefined, userBio is null
return <UserProfile userName={undefined} userBio={null} userAge={6} />;
}
Explanation
{ userName || <div>Error: You need to provide the user name</div>}!Here, the<strong>||</strong>operator is used to provide a default value if userName is falsy (e.g., null, undefined, false, 0, "", or NaN).`<strong>{userBio && <p>{userBio}</p>}</strong>: This line uses the<strong>&&</strong>operator to check if userBio is truthy. If it is, it renders the <p> element with userBio. If userBio is falsy, nothing is rendered from this expression (renders “false”, which is empty).
Key Points
The && operator is ideal for conditional rendering. It only renders the component or element if the condition is truthy.
The || operator is perfect for setting default values because it stops at and returns the first truthy value it finds, or the last value if all are falsy.
This use of logical operators makes your code more readable and concise, especially in React where such patterns are very common for conditional rendering and default values.
No hints available.