The new Skill-Wanderer Dojo is in active development. Until we finish the migration, the old dojo lives at legacy-dojo.skill-wanderer.com.

Lesson 11 of 15

Dynamic CSS Classes

Lesson Updated: Apr 28, 2026

Requirement

Learn how to use conditional logic to toggle CSS classes (e.g., adding an "active" class to a clicked button).

Assignments (Start First)

  1. Simple beginner UI task: Create a ToggleButton. Use state to track a boolean. If true, apply a btn-active class. If false, apply a btn-inactive class.
  2. Slightly improved version: Instead of completely swapping classes, keep a base btn class always applied, and append the dynamic class using template literals: btn ${isActive ? "btn-active" : ""}.
  3. Practical real-world component: Build a TabNavigation component with 3 tabs. Use state to track the active tab index. Map over an array of tab names, applying an "active" class only to the currently selected tab.
  4. "The Escalation": Create a PasswordStrength indicator. As the user types in an input, calculate the length. Apply "weak" (red), "medium" (yellow), or "strong" (green) classes to a progress bar div based on the length.

Lessons (Optional)

  • Template Literals: The easiest way to combine static and dynamic classes in JSX is using backticks and ${}.
  • Boolean Logic: You can use standard ternary operators directly inside the className string.

The Summary and Quizzes

  1. Concept explanation: Dynamic classes bridge the gap between React's state and CSS's visual styling, allowing your UI to react visually to data changes.
  2. Why it works in React: When state changes, React recalculates the className string and updates the DOM element's class attribute, triggering the browser to apply the new CSS rules.
  3. Challenge question: How would you write the className prop using template literals to always include "card" and conditionally include "card-highlighted" if isNew is true?