Introduction
Conditional rendering lets your app show or hide parts based on what is happening. It helps make your app smart and interactive.
Conditional rendering lets your app show or hide parts based on what is happening. It helps make your app smart and interactive.
return condition ? <ComponentA /> : <ComponentB />; // or using && operator return condition && <Component />;
function Greeting({ isLoggedIn }) { return isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>; }
function Loading({ isLoading }) { return isLoading ? <p>Loading...</p> : null; }
This app shows a login or logout button and message based on whether the user is logged in. Clicking the button switches the state and updates the view.
import React, { useState } from 'react'; function App() { const [isLoggedIn, setIsLoggedIn] = useState(false); return ( <div> {isLoggedIn ? ( <> <h1>Welcome back!</h1> <button onClick={() => setIsLoggedIn(false)}>Logout</button> </> ) : ( <> <h1>Please sign in.</h1> <button onClick={() => setIsLoggedIn(true)}>Login</button> </> )} </div> ); } export default App;
Conditional rendering keeps your UI clean and relevant to the user.
Always return valid React elements or null when condition is false.
Conditional rendering controls what the user sees based on app state.
Use ternary or && operators to show or hide components easily.
This makes your app interactive and user-friendly.
{condition && <Component />} renders the component only if condition is true.{condition && <Component />} matches the correct syntax exactly. {condition && &<Component />} has an extra & symbol. {condition ? <Component /> : null} uses ternary, which is correct but not && syntax. {condition ? <Component />} is incomplete ternary syntax.function Greeting({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>}
</div>
);
}isLoggedIn is false?isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>. If isLoggedIn is true, it shows "Welcome back!"; otherwise, it shows "Please sign in."false to the conditionisLoggedIn is false, the component renders the second part: <h1>Please sign in.</h1>.function ShowMessage({ show }) {
return (
<div>
{show ? <p>Hello!</p>}
</div>
);
}{show ? <p>Hello!</p>} which is incomplete because ternary requires both true and false parts separated by a colon.{show ? <p>Hello!</p> : null} or another expression after colon.isLoggedIn and isAdmin are true.{isLoggedIn && isAdmin && <AdminMessage />} uses isLoggedIn && isAdmin && <AdminMessage />, which renders the message only if both are true. {isLoggedIn ? <AdminMessage /> : <LoginPrompt />} shows message if logged in regardless of admin. {isAdmin ? <AdminMessage /> : null} ignores logged-in status. {isLoggedIn || isAdmin ? <AdminMessage /> : null} uses OR, showing message if either is true, which is incorrect.Pass the test and this pattern moves unknown