Bird
Raised Fist0
NextJSframework~20 mins

Conditional styling patterns in NextJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Conditional Styling Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the rendered background color of the button?

Consider this Next.js functional component using conditional styling with Tailwind CSS:

import React, { useState } from 'react';

export default function ColorButton() {
  const [active, setActive] = useState(false);
  return (
    <button
      className={`px-4 py-2 font-bold text-white rounded ${active ? 'bg-green-500' : 'bg-red-500'}`}
      onClick={() => setActive(!active)}
      aria-pressed={active}
    >
      {active ? 'Active' : 'Inactive'}
    </button>
  );
}

What background color will the button have when first rendered?

NextJS
import React, { useState } from 'react';

export default function ColorButton() {
  const [active, setActive] = useState(false);
  return (
    <button
      className={`px-4 py-2 font-bold text-white rounded ${active ? 'bg-green-500' : 'bg-red-500'}`}
      onClick={() => setActive(!active)}
      aria-pressed={active}
    >
      {active ? 'Active' : 'Inactive'}
    </button>
  );
}
AThe button has no background color.
BThe button has a green background (bg-green-500).
CThe button has a red background (bg-red-500).
DThe button background color toggles rapidly on render.
Attempts:
2 left
💡 Hint

Look at the initial state value of active and how it affects the className.

📝 Syntax
intermediate
2:00remaining
Which option correctly applies conditional inline styles in Next.js?

Given this Next.js component snippet, which option correctly applies a blue text color only when isBlue is true?

function Text({ isBlue }) {
  return (
    <p style={/* your code here */}>Hello</p>
  );
}
NextJS
function Text({ isBlue }) {
  return (
    <p style={/* your code here */}>Hello</p>
  );
}
A{ color: isBlue || 'blue' }
B{ color: isBlue && 'blue' }
C{ color: isBlue ? 'blue' : 'false' }
D{ color: isBlue ? 'blue' : undefined }
Attempts:
2 left
💡 Hint

Remember that inline style values must be strings or valid CSS values. Using false or undefined affects rendering differently.

🔧 Debug
advanced
2:00remaining
Why does this conditional className not update on state change?

Examine this Next.js component:

import { useState } from 'react';

export default function Toggle() {
  const [on, setOn] = useState(false);

  function toggle() {
    on = !on;
  }

  return (
    <button className={on ? 'bg-blue-500' : 'bg-gray-500'} onClick={toggle}>
      {on ? 'On' : 'Off'}
    </button>
  );
}

Why does clicking the button not change its background color?

NextJS
import { useState } from 'react';

export default function Toggle() {
  const [on, setOn] = useState(false);

  function toggle() {
    on = !on;
  }

  return (
    <button className={on ? 'bg-blue-500' : 'bg-gray-500'} onClick={toggle}>
      {on ? 'On' : 'Off'}
    </button>
  );
}
ADirectly assigning to 'on' does not update React state; use setOn instead.
BThe initial state is true, so the color never changes.
CThe toggle function is never called because onClick is misspelled.
DThe className syntax is invalid and causes a runtime error.
Attempts:
2 left
💡 Hint

Think about how React state variables should be updated.

🧠 Conceptual
advanced
2:00remaining
What is the advantage of using clsx or classnames for conditional styling?

In Next.js projects, libraries like clsx or classnames are often used for conditional class names. What is the main advantage of using them?

AThey allow combining multiple class names conditionally in a clean, readable way.
BThey automatically optimize CSS for faster loading.
CThey enable inline styles to be written as JavaScript objects.
DThey replace the need for CSS frameworks like Tailwind CSS.
Attempts:
2 left
💡 Hint

Think about how you manage multiple classes that depend on conditions.

❓ state_output
expert
3:00remaining
What is the final rendered text and color after these state updates?

Consider this Next.js component:

import { useState, useEffect } from 'react';

export default function Status() {
  const [status, setStatus] = useState('idle');

  useEffect(() => {
    if (status === 'idle') {
      setStatus('loading');
    } else if (status === 'loading') {
      setTimeout(() => setStatus('done'), 100);
    }
  }, [status]);

  return (
    <div className={
      status === 'idle' ? 'text-gray-500' :
      status === 'loading' ? 'text-yellow-500' :
      'text-green-500'
    }>
      {status}
    </div>
  );
}

After the component mounts and all state updates finish, what text and text color class will be rendered?

NextJS
import { useState, useEffect } from 'react';

export default function Status() {
  const [status, setStatus] = useState('idle');

  useEffect(() => {
    if (status === 'idle') {
      setStatus('loading');
    } else if (status === 'loading') {
      setTimeout(() => setStatus('done'), 100);
    }
  }, [status]);

  return (
    <div className={
      status === 'idle' ? 'text-gray-500' :
      status === 'loading' ? 'text-yellow-500' :
      'text-green-500'
    }>
      {status}
    </div>
  );
}
AText: 'idle' with class 'text-gray-500'.
BText: 'done' with class 'text-green-500'.
CText: 'loading' with class 'text-yellow-500'.
DText: 'done' with class 'text-yellow-500'.
Attempts:
2 left
💡 Hint

Consider how useEffect triggers on state changes and the timing of setTimeout.

Practice

(1/5)
1. In Next.js, which is the simplest way to apply a CSS class conditionally based on a boolean isActive inside a component's JSX?
easy
A. <div className='active' if={isActive}>Content</div>
B. <div className={isActive ? 'active' : ''}>Content</div>
C. <div className={if isActive then 'active'}>Content</div>
D. <div className={isActive && 'active' || 'inactive'}>Content</div>

Solution

  1. Step 1: Understand JSX conditional class syntax

    In JSX, you can use JavaScript expressions inside curly braces. The ternary operator condition ? valueIfTrue : valueIfFalse is a common way to apply classes conditionally.
  2. 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.
  3. Final Answer:

    <div className={isActive ? 'active' : ''}>Content</div> -> Option B
  4. Quick Check:

    Use ternary operator for conditional classes = A [OK]
Hint: Use ternary inside className for simple true/false styling [OK]
Common Mistakes:
  • Using invalid JSX syntax like 'if' inside attributes
  • Confusing logical AND/OR for conditional classes
  • Forgetting to use curly braces for JS expressions
2. Which of the following is the correct syntax to conditionally add multiple CSS classes in Next.js JSX using template literals when isActive and isDisabled are booleans?
easy
A. className={['btn', isActive && 'active', isDisabled && 'disabled'].join(' ')}
B. className='btn' + (isActive ? ' active' : '') + (isDisabled ? ' disabled' : '')
C. className={`btn ${isActive && 'active'} ${isDisabled && 'disabled'}`}
D. className={btn isActive ? 'active' : '' isDisabled ? 'disabled' : ''}

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    className={`btn ${isActive && 'active'} ${isDisabled && 'disabled'}`} -> Option C
  4. Quick Check:

    Template literals with ${condition && 'class'} = C [OK]
Hint: Use backticks and ${condition && 'class'} for multiple classes [OK]
Common Mistakes:
  • Forgetting curly braces around JSX expressions
  • Using invalid syntax mixing strings and expressions
  • Not handling false values rendering as 'false' string
3. Given this Next.js component code snippet, what will be the rendered class attribute when isActive is false and isDisabled is true?
function Button({ isActive, isDisabled }) {
  return (
    <button className={`btn ${isActive ? 'active' : ''} ${isDisabled ? 'disabled' : ''}`}>Click</button>
  );
}
medium
A. class="btn disabled"
B. class="btn"
C. class="btn active "
D. class="btn active disabled"

Solution

  1. Step 1: Substitute boolean values into the template literal

    Since isActive is false, isActive ? 'active' : '' becomes an empty string. Since isDisabled is true, isDisabled ? 'disabled' : '' becomes 'disabled'.
  2. Step 2: Combine the strings with spaces

    The final className string is btn disabled (note the double space between 'btn' and 'disabled' due to empty string). This renders as class="btn disabled", which browsers treat as btn disabled.
  3. Final Answer:

    class="btn disabled" -> Option A
  4. Quick Check:

    False condition yields empty string, true yields class = D [OK]
Hint: Replace ternary with values, watch spaces in template literals [OK]
Common Mistakes:
  • Assuming false condition adds 'active' class
  • Ignoring extra spaces in class string
  • Confusing true/false in ternary expressions
4. Identify the error in this Next.js JSX snippet for conditional styling and select the fix:
function Alert({ isError }) {
  return <div className={isError ? 'error' : 'success'} else='hidden'>Message</div>;
}
medium
A. Wrap the div in a ternary operator outside JSX
B. Replace else='hidden' with className='hidden'
C. Change to {isError && 'error' || 'success'} and keep else attribute
D. Remove else='hidden' because JSX does not support 'else' attribute

Solution

  1. Step 1: Identify invalid JSX attribute usage

    JSX does not support an else attribute on elements. Conditional logic must be inside curly braces.
  2. Step 2: Fix by removing invalid attribute

    Removing else='hidden' leaves a valid ternary expression for className. To conditionally add 'hidden', use nested ternary or other logic inside className.
  3. Final Answer:

    Remove else='hidden' because JSX does not support 'else' attribute -> Option D
  4. Quick Check:

    JSX attributes must be valid props, no 'else' attribute = A [OK]
Hint: JSX attributes can't have 'else'; use ternary inside className [OK]
Common Mistakes:
  • Trying to use 'else' as an attribute in JSX
  • Not wrapping conditional logic inside curly braces
  • Confusing HTML attributes with JSX props
5. You want to apply conditional styling in a Next.js component where the class '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?
hard
A. className={isSelected && count > 0 ? 'item highlight' : 'item'}
B. className={`item ${isSelected && count > 0 ? 'highlight' : ''}`}
C. className={`item ${isSelected && count > 0 && 'highlight'}`}
D. className={`item ${isSelected ? count > 0 ? 'highlight' : '' : ''}`}

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    className={isSelected && count > 0 ? 'item highlight' : 'item'} -> Option A
  4. Quick Check:

    Use full string ternary for multiple conditions = B [OK]
Hint: Use full string ternary to avoid false or empty class names [OK]
Common Mistakes:
  • Returning false or empty strings inside template literals
  • Nesting ternaries making code hard to read
  • Using logical AND that outputs boolean in className
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard