Name | Progress |
---|---|
Introduction | Not Read |
๐ฐ Player | Not Read |
Name | Progress |
---|---|
Software Installation | Not Read |
Project Setup | Not Read |
Running and Testing | Not Read |
React and ReactDOM | Not Read |
๐ก Assignment 1: Welcome Message | Not Attempted |
Submissions | Not Read |
Name | Progress |
---|---|
Pure Components - memo | Not Read |
Lifecycle - useEffect | Not Read |
Expensive? - useMemo | Not Read |
DOM Interactions - useRef | Not Read |
forwardRef | Not Read |
useImperativeHandle | Not Read |
๐พ useImperativeHandle | Not Attempted |
Context | Not Read |
useCallback | Not Read |
useId | Not Read |
useReducer | Not Read |
Name | Progress |
---|---|
Database | Not Read |
NextAuth and Github Authentication | Not Read |
Prisma and ORM | Not Read |
Project Setup | Not Read |
Project Authentication | Not Read |
Name | Progress |
---|---|
APIs | Not Read |
APIs - Slides | Not Attempted |
Rest APIs | Not Read |
Rest APIs - Express.js | Not Read |
ReastAPIs - Next.js | Not Read |
Securing APIs | Not Read |
Securing APIs - NextAuth | Not Read |
Name | Progress |
---|---|
tRPC | Not Read |
tRPC - Routers | Not Read |
tRPC - Server Rendering | Not Read |
tRPC - Client Rendering | Not Read |
Persisting Data | Not Read |
Assignment 3: APIs | Not Read |
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.
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.
If the age is under 18, we return UI with a funny greeting
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!
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).
The truthy statements will have "true" value in the boolean expression. For example, any non-zero number or string will have "true" value.
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.
Consequently, all these expressions are boolean expressions with truthy and falsy values. Pause the presentation and see if you can get the answers right.
The AND expression returns the last value only if all other values are truthy
The OR expression returns the first truthy element
Did you get the combined expression right?
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.
For example, React does not render boolean values and shows only empty value.
Similarly, null or undefined values React also ignores and does not render.
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.
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.
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.
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.
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 ...
... a condition in form of a boolean expression ...
... value returned if condition is true ...
... and a value returned if condition is false.
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.
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.
The component accepts three parameters: userName, userBio and userAge
The first ternary operator renders greeting based on use age.
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!
Last, we either existing user's bio, or show that bio is not available,
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.
We can further simplify our example component by using and, or operators and logical expressions. Let's take a look!
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.
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.
This AND chain returns value "Tomas" as all values in the chain are truthy, so the last value is returned.
Similarly, this AND chain returns value C as values "A" and "B" are truthy.
Last, this OR chain will return value "Tomas" as it is a truthy value, and all the previous falsy values are ignored.
Let's take a look at how we can use logical chaining to further simplify our component.
We will use ternary operator to decide the form of greeting based on user age.
But, we use OR expression to render the user name or the warning that user name is missing.
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!
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!
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.
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.
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} />;
}
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.
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โ ๏ธ 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.
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.
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} />;
}
{ 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).
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.