Introduction
Welcome to Day 7 of our 30-day blog series on React.js! Today, we'll explore conditional rendering in React, which allows us to render different components or UI elements based on certain conditions. Conditional rendering is a powerful feature that enables us to create dynamic and interactive user interfaces.
Conditional Rendering with if Statements
In React, we can use traditional JavaScript if statements to conditionally render components or elements. Here's an example:
function Greeting({ isLoggedIn }) {
if (isLoggedIn) {
return <p>Welcome back!</p>;
} else {
return <p>Please sign in.</p>;
}
}
The
Greeting
component renders a welcome message if the user is logged in, or a sign-in message if the user is not logged in.The condition isLoggedIn determines which message to render.
Conditional Rendering with Ternary Operator
We can also use the ternary operator ('condition ? trueValue : falseValue')
for more concise conditional rendering:
function Greeting({ isLoggedIn }) {
return isLoggedIn ? <p>Welcome back!</p> : <p>Please sign in.</p>;
}
Conditional Rendering with Logical && Operator
Another approach for conditional rendering is using the logical &&
operator, especially for rendering elements based on a single condition:
function Greeting({ isLoggedIn }) {
return isLoggedIn && <p>Welcome back!</p>;
}
In the above example, the paragraph element is rendered only if isLoggedIn
is true
.
Conditional Rendering with Switch Statement
For more complex conditional rendering, we can use a switch
statement:
function StatusBadge({ status }) {
switch (status) {
case 'active':
return <span className="badge badge-success">Active</span>;
case 'inactive':
return <span className="badge badge-danger">Inactive</span>;
default:
return null;
}
}
In the above example, the StatusBadge
component renders different badge styles based on the status
prop.
Conditional rendering is a powerful feature in React that allows us to render different components or elements based on certain conditions. Whether using if
statements, ternary operators, logical &&
operators, or switch
statements, understanding how to conditionally render components is essential for building dynamic and interactive user interfaces.
Stay tuned for tomorrow's post, where we'll dive deeper into working with lists and keys in React and how to efficiently render lists of data.
Top comments (0)