Conditional styling lets you change how things look based on some condition. It helps make your app more interactive and user-friendly.
Conditional styling patterns in NextJS
const className = condition ? 'class-true' : 'class-false'; // In JSX <div className={className}>Content</div>
isActive.const isActive = true; const className = isActive ? 'bg-blue-500 text-white' : 'bg-gray-200 text-black'; return <button className={className}>Click me</button>;
const isDisabled = false; return <button className={`btn ${isDisabled ? 'opacity-50 cursor-not-allowed' : ''}`}>Submit</button>;
clsx library to add classes based on multiple conditions cleanly.import clsx from 'clsx'; const isError = true; const isFocused = false; return <input className={clsx('input', { 'border-red-500': isError, 'border-blue-500': isFocused })} />;
This Next.js component shows a button that toggles between ON and OFF states. The button color changes green when ON and gray when OFF. It also uses accessible attributes and focus styles for keyboard users.
import { useState } from 'react'; export default function ToggleButton() { const [isOn, setIsOn] = useState(false); return ( <button aria-pressed={isOn} onClick={() => setIsOn(!isOn)} className={`px-4 py-2 rounded transition-colors duration-300 focus:outline-none focus:ring-2 focus:ring-offset-2 ${isOn ? 'bg-green-600 text-white' : 'bg-gray-300 text-black'}`} > {isOn ? 'ON' : 'OFF'} </button> ); }
Always use semantic HTML and ARIA attributes like aria-pressed for buttons that toggle states.
Use transition classes or CSS to smoothly animate style changes for better user experience.
Consider accessibility: ensure color contrast is good and keyboard focus styles are visible.
Conditional styling changes how elements look based on state or conditions.
Use JavaScript expressions inside JSX to apply different classes or styles.
Combine multiple conditions cleanly with template literals or helper libraries like clsx.
Practice
isActive inside a component's JSX?Solution
Step 1: Understand JSX conditional class syntax
In JSX, you can use JavaScript expressions inside curly braces. The ternary operatorcondition ? valueIfTrue : valueIfFalseis a common way to apply classes conditionally.Step 2: Evaluate each option's syntax
<div className={isActive ? 'active' : ''}>Content</div>uses the ternary operator correctly. Options B and C use invalid JSX syntax.<div className={isActive && 'active' || 'inactive'}>Content</div>uses a logical expression that can cause unexpected results.Final Answer:
<div className={isActive ? 'active' : ''}>Content</div> -> Option BQuick Check:
Use ternary operator for conditional classes = A [OK]
- Using invalid JSX syntax like 'if' inside attributes
- Confusing logical AND/OR for conditional classes
- Forgetting to use curly braces for JS expressions
isActive and isDisabled are booleans?Solution
Step 1: Understand template literals with conditional classes
Template literals use backticks and allow embedding expressions with ${}. Using logical AND returns the class name if true or false (which renders as the string 'false') if false.Step 2: Check each option's syntax
className={`btn ${isActive && 'active'} ${isDisabled && 'disabled'}`}correctly uses template literals with logical AND.className='btn' + (isActive ? ' active' : '') + (isDisabled ? ' disabled' : '')uses string concatenation but misses curly braces for JSX expression.className={['btn', isActive && 'active', isDisabled && 'disabled'].join(' ')}uses an array join which works but is less common.className={btn isActive ? 'active' : '' isDisabled ? 'disabled' : ''}is invalid JSX syntax.Final Answer:
className={`btn ${isActive && 'active'} ${isDisabled && 'disabled'}`} -> Option CQuick Check:
Template literals with ${condition && 'class'} = C [OK]
- Forgetting curly braces around JSX expressions
- Using invalid syntax mixing strings and expressions
- Not handling false values rendering as 'false' string
isActive is false and isDisabled is true?
function Button({ isActive, isDisabled }) {
return (
<button className={`btn ${isActive ? 'active' : ''} ${isDisabled ? 'disabled' : ''}`}>Click</button>
);
}Solution
Step 1: Substitute boolean values into the template literal
SinceisActiveis false,isActive ? 'active' : ''becomes an empty string. SinceisDisabledis true,isDisabled ? 'disabled' : ''becomes 'disabled'.Step 2: Combine the strings with spaces
The final className string isbtn disabled(note the double space between 'btn' and 'disabled' due to empty string). This renders asclass="btn disabled", which browsers treat asbtn disabled.Final Answer:
class="btn disabled" -> Option AQuick Check:
False condition yields empty string, true yields class = D [OK]
- Assuming false condition adds 'active' class
- Ignoring extra spaces in class string
- Confusing true/false in ternary expressions
function Alert({ isError }) {
return <div className={isError ? 'error' : 'success'} else='hidden'>Message</div>;
}Solution
Step 1: Identify invalid JSX attribute usage
JSX does not support anelseattribute on elements. Conditional logic must be inside curly braces.Step 2: Fix by removing invalid attribute
Removingelse='hidden'leaves a valid ternary expression for className. To conditionally add 'hidden', use nested ternary or other logic inside className.Final Answer:
Removeelse='hidden'because JSX does not support 'else' attribute -> Option DQuick Check:
JSX attributes must be valid props, no 'else' attribute = A [OK]
- Trying to use 'else' as an attribute in JSX
- Not wrapping conditional logic inside curly braces
- Confusing HTML attributes with JSX props
'highlight' should be added only if isSelected is true and count is greater than zero. Which of these is the best way to write the className attribute to handle this condition cleanly?Solution
Step 1: Analyze each option's logic and readability
className={`item ${isSelected && count > 0 ? 'highlight' : ''}`}uses a logical AND combined with ternary inside template literal, which can be confusing and may produce unexpected results.className={`item ${isSelected ? count > 0 ? 'highlight' : '' : ''}`}nests ternaries, which reduces readability.className={`item ${isSelected && count > 0 && 'highlight'}`}uses logical AND but if false returns false which renders as 'false' string in className.className={isSelected && count > 0 ? 'item highlight' : 'item'}uses a clear ternary outside template literal, returning full class strings, which is clean and safe.Step 2: Choose the best practice for conditional classes
className={isSelected && count > 0 ? 'item highlight' : 'item'}clearly returns either 'item highlight' or 'item' string, avoiding false or empty strings in className, making it the best pattern for this condition.Final Answer:
className={isSelected && count > 0 ? 'item highlight' : 'item'} -> Option AQuick Check:
Use full string ternary for multiple conditions = B [OK]
- Returning false or empty strings inside template literals
- Nesting ternaries making code hard to read
- Using logical AND that outputs boolean in className
Ready to prove it?
Pass the test and this pattern moves unknown
