Conditional Rendering is the technique used in React to display different elements or components based on certain conditions (e.g., a user’s login status, a loading state, or a configuration setting). Since JSX is JavaScript, you can use standard JavaScript operators to implement this logic directly within your markup.
1. The if Statement (Outside JSX)
The standard JavaScript if statement is the simplest way to control rendering. However, you cannot place if statements directly inside JSX. Instead, you use them before the return statement to decide which JSX should be returned.
Execution Example: Early Return
In your my-first-app/src directory:
- Open the main file,
App.js. - Replace its content with the following code:
import React, { useState } from 'react';
function UserGreeting({ isLoggedIn }) {
if (!isLoggedIn) {
// 1. If the condition is false, return a component early.
return <h1>Please log in to continue.</h1>;
}
// 2. If the condition is true, proceed and return the full content.
return (
<div>
<h1>Welcome Back, Authorized User!</h1>
<button>Access Dashboard</button>
</div>
);
}
function App() {
// Use state to toggle the login status
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<div className="ConditionalDemo">
<UserGreeting isLoggedIn={isLoggedIn} />
{/* Button to toggle the state */}
<button onClick={() => setIsLoggedIn(!isLoggedIn)}>
{isLoggedIn ? 'Log Out' : 'Log In'}
</button>
</div>
);
}
export default App;
- Local Execution: Run
npm start. - Observation: The
UserGreetingcomponent renders entirely different content based on theisLoggedInprop, demonstrating the “Early Return” pattern for conditional logic.
2. The Ternary Operator (? :)
For inline conditional rendering where you need to switch between two different elements, the JavaScript Ternary Operator is the preferred method inside JSX.
Syntax:
condition ? element_if_true : element_if_false
Execution Example: Inline Toggle
Use the same App.js file and note how the button text toggles using the ternary operator:
// ... inside the App component return statement ...
<button onClick={() => setIsLoggedIn(!isLoggedIn)}>
{/* The Ternary Operator determines the button text */}
{isLoggedIn ? 'Log Out' : 'Log In'}
</button>
// ...
3. Logical AND Operator (&&)
If you only want to render an element if a condition is true (and render nothing if the condition is false), you can use the JavaScript Logical AND Operator (&&).
React evaluates the expression from left to right:
- If the left side (
condition) is false, React stops and renders nothing. - If the left side (
condition) is true, React proceeds and renders the element on the right side.
Execution Example: Showing an Alert
Modify the App.js component again:
// ... inside the App component return statement ...
<UserGreeting isLoggedIn={isLoggedIn} />
{/* 1. Show the alert ONLY IF isLoggedIn is true */}
{isLoggedIn && (
<div style={{ backgroundColor: 'yellow', padding: '10px' }}>
<p>Alert: Your session is active.</p>
</div>
)}
{/* 2. Show the warning ONLY IF isLoggedIn is false */}
{!isLoggedIn && (
<div style={{ backgroundColor: 'orange', padding: '10px' }}>
<p>Warning: Please sign in to secure your data.</p>
</div>
)}
<button onClick={() => setIsLoggedIn(!isLoggedIn)}>
{isLoggedIn ? 'Log Out' : 'Log In'}
</button>
// ...
The Logical AND operator is widely used for rendering optional elements, such as alerts, loading spinners, or error messages.
