Conditional Rendering
Conditional rendering in React allows you to render different UI elements or components based on certain conditions or state values. This is essential for creating dynamic and responsive user interfaces.
Using if-else Statements Inside Components
You can write standard JavaScript if-else
logic inside your component function to decide what to render.
function UserGreeting(props) {
if (props.isLoggedIn) {
return <h3>Welcome back, User!</h3>;
} else {
return <h3>Please log in to continue.</h3>;
}
}
Using Ternary Operator for Inline Conditions
For shorter conditions, you can use JavaScript’s ternary operator inside JSX. It keeps your code concise and readable.
function Greeting(props) {
return (
<div>
{props.isLoggedIn ? <h3>Hello, User!</h3> : <h3>Welcome, Guest!</h3>}
</div>
);
}
Using Logical && Operator for Conditional Inclusion
You can use the logical &&
operator to render a component or element only if a condition is true.
function Mailbox(props) {
const unreadMessages = props.unreadMessages;
return (
<div>
<h3>Hello!</h3>
{unreadMessages.length &&
<h4>You have {unreadMessages.length} unread messages.</h4>}
</div>
);
}
Best Practices & Tips
- Keep conditions simple and readable.
- Use separate small components if the conditional rendering logic becomes complex.
- Avoid deeply nested ternary operators as they reduce code clarity.
- Leverage short-circuiting (
&&
) for simple checks.
Try This: Build a toggle button that switches between showing “Login” and “Logout” states!