Adding Dynamic Styles
Dynamic styles are styles that change based on your component's data or state, such as highlighting a selected item, colouring an invalid input red, or setting a progress bar's width from a number. In React you do this by computing the className or the style prop with JavaScript during rendering, so the look updates automatically whenever the data changes.
Switching classes with conditions
The cleanest approach is to keep every visual variant in CSS and let React choose which classes apply. Since className is just a string, you can build it with a ternary or a template literal. When state changes, React re-renders and the new class string is applied to the DOM element.
import { useState } from "react";
import "./TaskList.css";
function TaskList({ tasks }) {
const [selectedId, setSelectedId] = useState(null);
return (
<ul className="task-list">
{tasks.map((task) => {
const classes = [
"task",
task.done ? "task--done" : "",
task.id === selectedId ? "task--selected" : "",
].join(" ").trim();
return (
<li
key={task.id}
className={classes}
onClick={() => setSelectedId(task.id)}
>
{task.title}
</li>
);
})}
</ul>
);
}
function ProgressBar({ percent }) {
const safe = Math.min(100, Math.max(0, percent));
return (
<div className="bar">
<div
className="bar__fill"
style={{ width: `${safe}%`, backgroundColor: safe < 30 ? "crimson" : "seagreen" }}
/>
</div>
);
}
When to use the style prop
Conditional classes cover on-and-off states well. Inline styles shine when the value is truly continuous, like a width percentage, a position from mouse coordinates, or a colour picked by the user. Writing a CSS class for every possible percentage would be impossible, so the ProgressBar computes the width directly.
Remember the style prop's rules: it takes an object, property names are camelCase (backgroundColor, not background-color), and values with units are strings. A plain number is treated as pixels for most size properties.
Helper libraries for long class lists
Building class strings by hand works but gets messy with many conditions. Small libraries such as clsx or classnames accept an object and include only keys whose values are true, for example clsx("task", { "task--done": task.done }). With CSS Modules, the same idea applies, using styles.done instead of plain strings.
Mistakes that break dynamic styling
A common one is writing className={isActive && "active"}. When isActive is false, the value becomes the boolean false, and React may warn about receiving a non-string value for a DOM attribute. A ternary that returns an empty string is safer.
Another frequent bug is forgetting the space when concatenating, as in "task" + (done ? "task--done" : ""), which produces the single class "tasktask--done". Join with spaces or use a template literal with a space between parts.
Finally, avoid storing derived styles in state. If the colour depends on percent, compute it during render as above; keeping a separate colour state means two values that can fall out of sync.
Using CSS variables
A neat middle ground is to pass a custom property through the style prop, such as style={{ "--accent": user.colour }}, and let your CSS use var(--accent) in several rules, including hover states that inline styles cannot express.
Takeaway: compute class names from state for discrete states, use the style object for continuous values, derive styles during render instead of storing them, and watch for missing spaces and stray false values.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.