Conditional rendering in React allows you to render different UI elements based on certain conditions, like state or props values.
Using if Statement
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <h1>Welcome Back!</h1>;
} else {
return <h1>Please Sign In</h1>;
}
}
Using Ternary Operator
function Greeting({ isLoggedIn }) {
return (
<h1>
{isLoggedIn ? "Welcome Back!" : "Please Sign In"}
</h1>
);
}
Using Logical && Operator
function Notification({ messages }) {
return (
<div>
{messages.length > 0 && <h2>You have {messages.length} messages</h2>}
</div>
);
}
Best Practices
- Keep conditional logic simple and readable
- Avoid deeply nested conditions
- Prefer ternary operators or logical && for inline rendering
- Lift complex logic to helper functions if needed
Conclusion
Conditional rendering makes React components dynamic and responsive, showing content based on user actions, props, or state changes.
Citations
https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP