Slide 1
-----------
Part 1: In this section, we will explore how you can render your component based on some condition, for example showing figures in red or green based on their value, or showing a different greeting based on your user's age or gender.
Slide 2
-----------
Part 1: 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.
Part 2: If the age is under 18, we return UI with a funny greeting
Part 3: If the age is over 18, we return UI with a formal greeting. But what if you want to specify more conditions with several sub-conditions? This approach would get problematic with each if-else branch. Let's take a look how to solve this!
Slide 3
-----------
Part 1: To dive deeper in conditional rendering, we need to talk about truthy and falsy values. In JavaScript, truthy and falsy values determine how values behave in boolean contexts (e.g., conditions like if statements).
Part 2: The truthy statements will have "true" value in the boolean expression. For example, any non-zero number or string will have "true" value.
Part 3: The falsy statements will have "false" value in the boolean expression. For example, the number 0, an empty string, or a null or undefined value will pose as false.
Slide 4
-----------
Part 1: Consequently, all these expressions are boolean expressions with truthy and falsy values. Pause the presentation and see if you can get the answers right.
Part 2: The AND expression returns the last value only if all other values are truthy
Part 3: The OR expression returns the first truthy element
Part 4: Did you get the combined expression right?
Slide 5
-----------
Part 1: Before we dive into alternative ways of how to conditionally render the component content you need to understand how ReactJS renders different truthy and falsy values.
Part 2: For example, React does not render boolean values and shows only empty value.
Part 3: Similarly, null or undefined values React also ignores and does not render.
Part 4: But, while 0 is also a falsy value, React does render it. This is important when testing for numeric values in logical chains, as we will show soon. Similarly, the NaN value renders the NaN string.
Part 5: Last, arrays render elements inside the array or nothing if array is empty.
Slide 6
-----------
Part 1: In React, the null coalescing operator is especially useful when setting default values for props or states that might be null or undefined. It helps ensure that your components render correctly even if the data isn't unavailable or something went wrong somewhere else in your code.
Part 2: 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. This operator returns the value before the two question marks if that value is not null or undefined. Otherwise, it returns the value after the two question marks.
Part 3: This approach ensures that your component always has valid data to display and avoids any potential issues or crashes that might occur if it tries to access null or undefined values.
Slide 7
-----------
Part 1: 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 ...
Part 2: ... a condition in form of a boolean expression ...
Part 3: ... value returned if condition is true ...
Part 4: ... and a value returned if condition is false.
Part 5: When we execute these examples, the first expression returns "Valeria" as the condition was true. The second condition returns "Loss" as the condition was false.
Slide 8
-----------
Part 1: 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.
Part 2: The component accepts three parameters: userName, userBio and userAge
Part 3: The first ternary operator renders greeting based on use age.
Part 4: The second ternary operator renders the user's name or shows an error that this data is missing. See that we can return JSX code in the ternary operator as well!
Part 5: Last, we either existing user's bio, or show that bio is not available,
Part 6: We render two different variations of the profile component, one with a young age and a specified name. The other with a missing name and older age.
Slide 9
-----------
Part 1: We can further simplify our example component by using and, or operators and logical expressions. Let's take a look!
Part 2: Logical expressions can operate over true or false and truthy and falsy values. The OR operator returns the first truthy value in the chain. In this case, the console prints the truthy value, Tomas, as the null value is falsy.
Part 3: The AND expression chain returns the last value if all previous values in the chain are truthy. If at least one value is not truthy it returns false. In our case, the null value is falsy, and the expression returns false.
Part 4: This AND chain returns value "Tomas" as all values in the chain are truthy, so the last value is returned.
Part 5: Similarly, this AND chain returns value C as values "A" and "B" are truthy.
Part 6: Last, this OR chain will return value "Tomas" as it is a truthy value, and all the previous falsy values are ignored.
Slide 10
-----------
Part 1: Let's take a look at how we can use logical chaining to further simplify our component.
Part 2: We will use ternary operator to decide the form of greeting based on user age.
Part 3: But, we use OR expression to render the user name or the warning that user name is missing.
Part 4: Last, we use the end operator to render the user's bio, or we will not emit any elements related to visualising the user's bio. Pretty cool huh!
Part 5: When we render these two components, we will see the correct welcome, user age and the rendered bio.
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 display Yo, otherwise plain old boring Welcome.
* 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.
Maggie is a generative AI that can help you understand the course content better. You can ask her questions about the lecture, and she will try to answer them. You can also see the questions asked by other students and her responses.
Join the discussion to ask questions, share your thoughts, and discuss with other learners