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)
- Simple beginner UI task: Create a
ToggleButton. Use state to track a boolean. If true, apply abtn-activeclass. If false, apply abtn-inactiveclass. - Slightly improved version: Instead of completely swapping classes, keep a base
btnclass always applied, and append the dynamic class using template literals:.btn ${isActive ? "btn-active" : ""} - Practical real-world component: Build a
TabNavigationcomponent 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. - "The Escalation": Create a
PasswordStrengthindicator. 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
classNamestring.
The Summary and Quizzes
- 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.
- Why it works in React: When state changes, React recalculates the
classNamestring and updates the DOM element's class attribute, triggering the browser to apply the new CSS rules. - Challenge question: How would you write the
classNameprop using template literals to always include "card" and conditionally include "card-highlighted" ifisNewis true?