javascript / beginner
Snippet
Conditional Rendering Using Inline Logical AND Operator
React allows conditional rendering using JavaScript's logical AND (&&) operator. When the left-side expression evaluates to true, the JSX on the right side is rendered; when false, React ignores it.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
function NotificationBanner({ unreadCount }) {const hasMessages = unreadCount > 0;return (<div>{hasMessages && (<p className="badge">You have {unreadCount} new messages!</p>)}</div>);}
react
Breakdown
1
const hasMessages = unreadCount > 0;
Evaluates a boolean condition checking whether there are unread messages.
2
{hasMessages && (
Uses the logical AND operator to conditionally evaluate and render the adjacent JSX markup.
3
<p className="badge">You have {unreadCount} new messages!</p>
Renders the message notification element only when hasMessages evaluates to true.