Menu
Coddy logo textTech

Show with &&

Part of the Fundamentals section of Coddy's React journey — lesson 34 of 42.

Often there's no else: you just want something to appear when a condition holds. The && trick handles show-or-nothing:

{unread > 0 && <span>You have {unread} new messages</span>}

How it works: && returns the right side when the left is true, and React renders it. When the left is false, nothing renders. It's the ternary with the : null chopped off:

{cond ? <X /> : null}   // same as
{cond && <X />}
challenge icon

Challenge

Easy

Show an inbox badge only when there's something to read. The component defines unread.

  1. Using &&, render a <span> with id="badge" and the text 3 new messages (build the number from the variable!), but only when unread is greater than 0.

Try it yourself

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="styles.css" />
    </head>
    <body>
        <div id="root"></div>
        <script type="module" src="main.jsx"></script>
    </body>
</html>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals