Conditional rendering in React means displaying elements or components based on certain conditions. It works just like regular JavaScript conditions — you decide what to show depending on state or variables.
For example, you show a “Login” button if a user is logged out, and a “Logout” button if the user is logged in.
✨ Conditional rendering = “Show this UI only when a condition is true.”
if statement – clear branching logic, often used before the return.(&&) – render something only when a condition is true.? : – quickly choose between two JSX blocks.if StatementsThe if statement is useful when you want very readable logic. You decide which JSX block to return based on props or state.
// Conditionally return different JSX using an if...else block
function Greeting(props) {
if (props.isLoggedIn) {
return <h2>Welcome back!</h2>;
} else {
return <h2>Please sign in.</h2>;
}
}
props.isLoggedIn is true → user sees “Welcome back!”.props.isLoggedIn is false → user sees “Please sign in.”.&&)The && operator lets you render a piece of UI only when a condition is true. If the condition is false, React ignores the JSX on the right-hand side.
// Show the message only when there is at least one notification
function Notifications({ count }) {
return (
<div>
<h3>Notifications</h3>
{count > 0 && <p>You have {count} new messages.</p>}
</div>
);
}
count is 0 → nothing is rendered after the heading.count is greater than 0 → the paragraph is rendered.? :)The ternary operator provides a compact way to choose between two JSX results. It is often used directly inside JSX for simple conditions.
// Use a ternary expression inside JSX to switch content
function UserStatus({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <h2>Welcome back!</h2> : <h2>Please log in.</h2>}
</div>
);
}
If isLoggedIn is true, the user sees “Welcome back!”. Otherwise, they see “Please log in.”. This is just a shorter version of if...else.
You can mix if, &&, and the ternary operator for more complex flows, such as dashboards where only admins can see some parts.
// Mix ternary and && to handle login and role-based messages
function Dashboard({ isLoggedIn, isAdmin }) {
return (
<div>
{isLoggedIn ? (
<>
<h2>Welcome User</h2>
{isAdmin && <p>You have admin access.</p>}
</>
) : (
<h2>Please login to continue.</h2>
)}
</div>
);
}
&& when you want to conditionally render something without an “else”.<AdminPanel /> component).isVisible, isLoggedIn, or hasAccess.&& only when it still feels readable.LoginControl with a boolean state isLoggedIn.if statement in the component logic and a ? : inside JSX for text changes.Goal: Practice using if, &&, and ternary operators to render different UI based on React state or props.