Ternaries for Attribute Values
What you'll learn: How to use ternary operators to conditionally set prop values based on state or conditions.
The Core Idea
You've already learned how ternaries can choose which component to render or what text to display. Now let's apply the same pattern to attribute values themselves. Instead of switching between two entire elements, you're switching between two possible values for a single prop.
The most common use case? The className prop:
<button className={isActive ? 'active' : 'inactive'}>
Click Me
</button>
If isActive is true, the button gets className="active". If false, it gets className="inactive".
Why This Matters
Imagine a navigation menu where the current page's link should be highlighted. You could write two separate <a> tags with different className values, but that duplicates everything else (the text, the href, event handlers). Instead, you conditionally set just the className:
<a href="/home" className={currentPage === 'home' ? 'nav-link-active' : 'nav-link'}>
Home
</a>
This works for any attribute: disabled={!isValid ? true : false}, style={isDark ? darkTheme : lightTheme}, aria-label={isOpen ? 'Close menu' : 'Open menu'}.
Analogy
Think of it like a light switch that doesn't turn the light off, but switches it between two different bulbs—one red, one blue. The fixture stays the same; only the bulb changes.
Key Takeaway: Use ternaries inside JSX attribute curly braces to conditionally assign prop values, keeping your element structure DRY while adapting behavior or styling dynamically.