Chapter 6: Conditional Rendering
Welcome back to "React Revolution"! In the previous chapter, we explored event handling in React, a fundamental skill for creating interactive applications. Today, we're going to dive into another key concept. This will allow you to control what gets displayed based on specific conditions, making your applications more dynamic and responsive.
6.1 What is Conditional Rendering?
Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like if
or the conditional (ternary) operator to create elements representing the current state, and React will update the UI to match them.
6.2 Basic Conditional Rendering
Let's start with a simple example. Suppose we have a component that shows a message based on whether a user is logged in or not.
import React, { useState } from 'react';
function Greeting() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const toggleLogin = () => {
setIsLoggedIn(!isLoggedIn);
};
return (
<div>
{isLoggedIn ? <h2>Welcome back!</h2> : <h2>Please sign in.</h2>}
<button onClick={toggleLogin}>
{isLoggedIn ? 'Logout' : 'Login'}
</button>
</div>
);
}
export default Greeting;
In this example:
We use the
useState
hook to manage theisLoggedIn
state.We use a ternary operator to conditionally render different messages based on the
isLoggedIn
state.We use the same ternary operator to change the button text between "Login" and "Logout".
6.3 Using If Statements
You can also use if statements for more complex conditions. Let's modify our previous example to include an admin user.
import React, { useState } from 'react';
function Greeting() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [isAdmin, setIsAdmin] = useState(false);
const toggleLogin = () => {
setIsLoggedIn(!isLoggedIn);
};
const toggleAdmin = () => {
setIsAdmin(!isAdmin);
};
let message;
if (isLoggedIn && isAdmin) {
message = <h2>Welcome, Admin!</h2>;
} else if (isLoggedIn) {
message = <h2>Welcome back!</h2>;
} else {
message = <h2>Please sign in.</h2>;
}
return (
<div>
{message}
<button onClick={toggleLogin}>
{isLoggedIn ? 'Logout' : 'Login'}
</button>
{isLoggedIn && (
<button onClick={toggleAdmin}>
{isAdmin ? 'Revoke Admin' : 'Grant Admin'}
</button>
)}
</div>
);
}
export default Greeting;
In this example:
We use the
isAdmin
state to track whether the user is an admin.We use an
if
statement to determine the message to display based on theisLoggedIn
andisAdmin
states.We conditionally render the "Grant Admin" / "Revoke Admin" button only if the user is logged in.
6.4 Using Logical && Operator
For simpler conditions, you can use the logical &&
operator. It allows you to render a component or element if a condition is true.
import React, { useState } from 'react';
function Notification() {
const [hasNotification, setHasNotification] = useState(true);
const clearNotification = () => {
setHasNotification(false);
};
return (
<div>
{hasNotification && <h2>You have new notifications!</h2>}
<button onClick={clearNotification}>
Clear Notification
</button>
</div>
);
}
export default Notification;
In this example:
We use the
hasNotification
state to track if there are new notifications.We use the logical
&&
operator to render the notification message only ifhasNotification
is true.
6.5 Returning Null
Sometimes you may want to hide a component completely. In such cases, you can return null
instead of rendering.
import React, { useState } from 'react';
function WarningBanner({ warn }) {
if (!warn) {
return null;
}
return (
<div>
<h2>Warning!</h2>
</div>
);
}
function App() {
const [showWarning, setShowWarning] = useState(true);
const toggleWarning = () => {
setShowWarning(!showWarning);
};
return (
<div>
<WarningBanner warn={showWarning} />
<button onClick={toggleWarning}>
{showWarning ? 'Hide' : 'Show'} Warning
</button>
</div>
);
}
export default App;
In this example:
The
WarningBanner
component returnsnull
if thewarn
prop is false, effectively hiding the component.The
App
component toggles theshowWarning
state to show or hide the warning message.
You've just learned the basics of conditional rendering in React! We covered:
Using the ternary operator for simple conditions.
Using if statements for more complex conditions.
Using the logical
&&
operator for concise conditional rendering.Returning
null
to hide components.
Understanding conditional rendering allows you to create dynamic and interactive user interfaces. Practice these techniques and experiment with your conditions to see how they affect your application's behavior.
Happy Coding!