The simplest approach: write normal CSS in a separate file and import it directly into your component file:
/* Button.css */
.primary-button {
background: #10b981;
color: white;
padding: 10px 20px;
border-radius: 8px;
}// Button.jsx
import "./Button.css";
function Button() {
return <button className="primary-button">Click Me</button>;
}These class names are global across your entire app โ two components using the same class name will share (and possibly clash with) each other's styles, which is the main limitation this approach has.
JSX also accepts a style attribute, but it expects a JavaScript object, not a CSS string โ property names use camelCase instead of hyphens:
function Button() {
return (
<button style={{ backgroundColor: "#10b981", padding: "10px 20px" }}>
Click Me
</button>
);
}Note the double curly braces: the outer {} is regular JSX expression syntax, and the inner {} is an actual JavaScript object literal.
function StatusBadge({ isActive }) {
return (
<span className={isActive ? "badge-green" : "badge-gray"}>
{isActive ? "Active" : "Inactive"}
</span>
);
}Building class name strings conditionally like this is extremely common in real UI, and eventually most teams reach for a small helper library (like clsx) to keep it clean once several conditions are involved.
Writing style={backgroundColor: "red"} instead of style={{ backgroundColor: "red" }} causes a syntax error โ the outer braces enter JSX expression mode, and you still need an actual JavaScript object literal (with its own braces) inside them.
Create a Button component that changes its background color between green and gray based on a boolean prop called isActive, using conditional className logic.
function Button({ isActive }) {
return (
<button className={isActive ? "btn-active" : "btn-inactive"}>
{isActive ? "Active" : "Inactive"}
</button>
);
}
export default Button;
Q Should I use CSS files or inline styles in React?
Regular CSS files (or CSS Modules for larger apps) are generally preferred for most styling, since they support pseudo-classes like :hover and media queries, which the inline style object syntax cannot handle directly.
Q What are CSS Modules?
CSS Modules (files named like Button.module.css) automatically scope class names to the specific component that imports them, preventing the global class-name clashes that plain CSS files can cause in larger apps.