Conditional Rendering
Ternary Operator
When you want to render A when a condition is true
or B if the condition is false
, you can use the ternary operator.
const App = () => {
const num = 1;
return (
<div>
<p>
The number is {num % 2 === 0 ? "even" : "odd"}
</p>
</div>
);
};
In addition to primitive values like the strings "even"
and "odd"
above, you can also conditionally render JSX and React Components.
const LoginButton = () => {
return <button>Login</button>;
};
const LogoutButton = () => {
return <button>Logout</button>;
};
const App = () => {
const loggedIn = false
return (
<div>
{ loggedIn ? <LoginButton /> : <LogoutButton /> }
</div>
);
};
Rendering Something Only When a Condition is true
true
Say you want to render the <WelcomeMessage />
component below only when a user is logged in. If they're not logged in, you don't want to render anything at all.
const WelcomeMessage = () => {
return <p>Welcome back!</p>
};
You can use null
on the false
side of the ternary operator
const App = () => {
return (
<div>
{ loggedIn ? <WelcomeMessage /> : null }
</div>
);
};
or use the Logical AND operator &&
and its short-circuit behaviour.
const App = () => {
return (
<div>
{ loggedIn && <WelcomeMessage /> }
</div>
);
};
Primitive Types JSX Won't Render
null
undefined
Booleans (
true
andfalse
)
Last updated
Was this helpful?