React FAQ: Top 75 Questions
12. What is Conditional Rendering in React?
Conditional rendering in React allows you to render different elements or components based on certain conditions. This is a fundamental concept for building dynamic user interfaces where parts of the UI need to appear or disappear depending on the application's state or props.
Common techniques for conditional rendering include:
-
ifstatements (outside JSX): You can use standard JavaScriptif/elsestatements within your component's function body (before thereturnstatement) to return different JSX based on a condition. -
Ternary Operator (
condition ? true : false): A concise way to render one thing if a condition is true, and another if it's false, directly within JSX. -
Logical
&&Operator (Short-Circuiting): If you want to render something only when a condition is true (and render nothing if it's false), you can use the logical&&operator. If the condition is true, the element after&&is rendered; otherwise, React ignores it. -
switchstatements: For more complex conditional logic with multiple possible outcomes, aswitchstatement can be used. - Element Variables: You can declare a variable to hold elements, and then conditionally assign JSX to it before rendering that variable.
import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';
// --- Component demonstrating various conditional rendering techniques ---
function UserStatus({ isLoggedIn, userRole }) {
// 1. Using if/else statement (outside JSX)
if (!isLoggedIn) {
return (
<div className="status-card swf-lsn-card">
<h3>User Status</h3>
<p>Please log in.</p>
</div>
);
}
// 2. Using Element Variables for different messages
let welcomeMessage;
if (userRole === 'admin') {
welcomeMessage = <p className="text-red-600 font-bold">Welcome, Administrator!</p>;
} else if (userRole === 'moderator') {
welcomeMessage = <p className="text-blue-600 italic">Welcome, Moderator!</p>;
} else {
welcomeMessage = <p>Welcome, User!</p>;
}
return (
<div className="status-card swf-lsn-card">
<h3>User Status</h3>
<p>You are currently logged in.</p>
{welcomeMessage} {/* Rendering the element variable */}
{/* 3. Using Ternary Operator */}
<p>
Your role is: <strong>{userRole ? userRole.toUpperCase() : 'N/A'}</strong>
</p>
{/* 4. Using Logical && Operator */}
{userRole === 'admin' && (
<p className="text-green-600 mt-2">You have full administrative privileges.</p>
)}
</div>
);
}
// --- App Component ---
function App() {
const [loggedIn, setLoggedIn] = useState(false);
const [role, setRole] = useState('user');
return (
<div className="app-container swf-lsn-container">
<h1>Conditional Rendering Demo</h1>
<div className="mb-4">
<button
onClick={() => setLoggedIn(!loggedIn)}
className="px-4 py-2 mr-2 rounded-md bg-purple-600 text-white"
>
{loggedIn ? 'Log Out' : 'Log In'}
</button>
<select
value={role}
onChange={(e) => setRole(e.target.value)}
className="px-3 py-2 rounded-md border border-gray-300"
>
<option value="user">User</option>
<option value="moderator">Moderator</option>
<option value="admin">Admin</option>
</select>
</div>
<UserStatus isLoggedIn={loggedIn} userRole={role} />
<div className="swf-lsn-list mt-8">
<p>
This example demonstrates various ways to conditionally render content
in React based on the <code>isLoggedIn</code> and <code>userRole</code> props.
</p>
</div>
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Explanation of the Code:
-
The
UserStatuscomponent receivesisLoggedInanduserRoleas props. -
ifstatement: At the very beginning, anif (!isLoggedIn)check determines if the user is logged in. If not, it immediately returns a "Please log in" message, preventing the rest of the component from rendering. -
Element Variables: The
welcomeMessagevariable is conditionally assigned different JSX elements based onuserRoleusing anif/else if/elsestructure. This variable is then rendered within the mainreturnstatement. -
Ternary Operator:
{userRole ? userRole.toUpperCase() : 'N/A'}is used to display the user's role in uppercase if it exists, otherwise "N/A". This is concise for simple true/false conditions. -
Logical
&&Operator:{userRole === 'admin' && (...) }ensures that the "You have full administrative privileges." paragraph is only rendered ifuserRoleis exactly 'admin'. If the condition is false, nothing is rendered. -
The
Appcomponent provides buttons and a dropdown to change theisLoggedInstatus anduserRole, allowing you to observe the conditional rendering in action.
