How to Use CSS in React
Connect React elements to CSS classes, choose when to use inline styles, and load stylesheets correctly across React projects.
To use CSS in React, give JSX elements a className, then define those classes in a CSS stylesheet. Use regular classes for reusable, predictable styles; use the style prop when a value depends on JavaScript data. How the CSS file is loaded depends on your project’s build tool or framework.
1. Add a stylesheet and use a CSS class
In JSX, React’s className prop corresponds to HTML’s class attribute. Write ordinary CSS selectors in a stylesheet:
/* Card.css */
.card {
padding: 1rem;
border: 1px solid #d1d5db;
border-radius: 0.5rem;
background: white;
}
.card__title {
margin: 0;
color: #111827;
}
// Card.jsx
import './Card.css';
export default function Card() {
return (
<article className="card">
<h2 className="card__title">Profile</h2>
<p>Account details and preferences.</p>
</article>
);
}
The CSS import is common in projects with a bundler that supports importing CSS from JavaScript. It is not a React language feature, and it will not work in every setup without configuration. React does not prescribe how CSS files are loaded.
Ways to load the stylesheet
- Bundler or framework: Follow its CSS instructions. Many setups allow importing a stylesheet from a component or application entry point.
- Plain HTML setup: Link the stylesheet from the document’s
<head>, for example<link rel="stylesheet" href="/styles.css">. The path must resolve to a file served by your app. - React 19: React supports rendering stylesheet
<link>and<style>components in the component tree. A link’sprecedenceprop lets React manage stylesheet ordering in the document head; identical linked stylesheets can be deduplicated. Use this when it fits your rendering architecture, rather than assuming it is required for every app.
Official guidance: React Quick Start explains that React does not prescribe how CSS files are added. See the React 19 link reference for stylesheet link behavior.
2. Choose classes or inline styles
Use a CSS class when the rule is known ahead of time, should be reused, or needs CSS features such as pseudo-classes and media queries. Use inline styles when a value comes from JavaScript, such as a size received as a prop. React recommends using the style attribute when styles depend on JavaScript variables.
| Need | Good starting point | Why |
|---|---|---|
| Reusable card layout or typography | CSS class | Keep the rule in one stylesheet and reuse its selector. |
| Value derived from data or a prop | Inline style for that value | Pass the dynamic value directly while keeping stable rules in CSS. |
| Hover, focus, responsive, or state selectors | CSS class | These are naturally expressed by stylesheet selectors and at-rules. |
| One-off calculated dimension | Inline style, often alongside a class | Separate the changing value from reusable presentation. |
These approaches can be combined. For example, an avatar can use a class for its shape and border while receiving its dimensions dynamically.
function Avatar({ size, src }) {
return (
<img
className="avatar"
style={{ width: size, height: size }}
src={src}
alt=""
/>
);
}
/* Avatar.css */
.avatar {
display: block;
border-radius: 50%;
object-fit: cover;
}
Here, size should be a CSS-compatible value such as 48 or "3rem". React renders numeric style values with px for properties that expect a length, except for CSS properties that are unitless.
3. Write inline styles correctly
The style prop takes a JavaScript object. Use camelCase property names instead of CSS’s hyphenated names, and use a second pair of braces in JSX: one pair for the JSX expression and one for the object.
function Notice() {
return (
<p style={{ backgroundColor: 'black', color: 'pink', padding: 12 }}>
Saved
</p>
);
}
background-colorbecomesbackgroundColor.- Numeric
padding: 12becomes12px. - Unitless properties, such as
opacity, remain numeric:opacity: 0.8. - For a value that needs a specific unit, pass a string:
width: '50%'orfontSize: '1.25rem'.
For TypeScript, type a reusable style object with React.CSSProperties:
import type { CSSProperties } from 'react';
const panelStyle: CSSProperties = {
backgroundColor: 'white',
padding: 16,
opacity: 1,
};
The React type reference documents style objects and CSSProperties.
4. Apply styles conditionally
Build the className string with ordinary JavaScript. Keep the base class stable and append a modifier class when a condition is true:
function Card({ selected }) {
const className = selected ? 'card card--selected' : 'card';
return (
<article className={className}>
<h2>Profile</h2>
</article>
);
}
.card {
border: 1px solid #d1d5db;
background: white;
}
.card--selected {
border-color: #2563eb;
box-shadow: 0 0 0 2px #bfdbfe;
}
For multiple independent conditions, template strings can keep the expression readable:
const className = [
'button',
primary && 'button--primary',
disabled && 'button--disabled',
].filter(Boolean).join(' ');
The optional classnames helper library can make longer conditional combinations easier to read, but simple cases need no dependency. React’s common components reference shows class string composition and mentions this helper.
5. Keep CSS predictable as the app grows
- Choose class names that describe the component or role, such as
profile-cardorprofile-card__title. - Keep stable presentation rules in CSS and pass only genuinely data-driven values through inline styles.
- Make sure the stylesheet is loaded by the application’s actual entry point or supported import path.
- When styles appear overridden, inspect selector specificity, source order, and whether the expected stylesheet loaded.
- Use your existing framework or build tool’s documented approach before introducing a new styling system. React itself does not select CSS Modules, CSS-in-JS, or utility classes for you.
6. Troubleshoot common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| A class’s styles do not apply | The JSX uses class, a misspelled class, or a selector that does not match. |
Use className="card" and check that the stylesheet selector is exactly .card. |
| Importing a CSS file causes a build error | The project’s toolchain does not support CSS imports at that location or needs configuration. | Follow the framework or bundler’s CSS-loading instructions, or link a served stylesheet from HTML. |
| Inline style property is ignored | The property name uses CSS hyphens or the object syntax is invalid. | Use camelCase, such as backgroundColor, and pass a JavaScript object to style. |
| A numeric value has the wrong unit | React adds px to numeric values for length properties, while some properties are unitless. |
Use a string with the intended unit, such as '50%', or pass a number where pixel length is intended. |
| Conditional styles never appear | The condition is false, or the resulting class string omits the modifier. | Inspect the rendered element’s class attribute and confirm the state or prop value. |
| Styles work locally but not after deployment | The stylesheet URL or asset path differs in the deployed app. | Check the browser network panel for a failed CSS request and use paths supported by the deployment setup. |
| Rules seem randomly overridden | Another selector has higher specificity or a later rule wins in source order. | Inspect computed styles, reduce competing selectors, and organize stylesheet order deliberately. |
7. Performance, reliability, and cost
For ordinary component styling, choose based on whether a rule is reusable or data-driven; the React guidance here does not establish a performance ranking among styling methodologies. Avoid generating a different styling system for values that can be represented as a small set of conditional classes. Keep stylesheet loading aligned with the project’s build and deployment setup so missing assets are caught early.
CSS and React have no per-request cost in a typical client-side app. Costs can arise from adopting additional styling tools or from the build and maintenance choices they introduce; the research does not support a universal cost comparison. If you need a rendered visual check of a page, an API can capture the deployed result.
8. Capture a rendered page while checking CSS
When styles look correct in the source but you need to inspect the actual rendered page, capture a screenshot of the page after deployment. [ScreenshotNeo](https://screenshotneo.com) is a website screenshot API and MCP server. It returns PNG, JPEG, WebP, or PDF from one GET request. The response includes page-verdict and billing headers; only clean shots are billed, while bot checks, blank pages, timeouts, failed loads, and cache hits cost nothing. See the ScreenshotNeo API documentation.
Or skip the browser setup
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
Replace the example URL with the page you want to inspect. ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots a month with no card, and paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.
9. FAQ
Does React require a CSS framework?
No. React works with ordinary CSS classes and leaves stylesheet loading to the project’s tools or framework.
Can I use CSS variables with React?
Yes. Define custom properties in CSS and consume them in stylesheet rules. For a value supplied by JavaScript, an inline style object can set a custom property, for example style={{ '--accent': color }}, with an appropriate type in TypeScript.
Should every style go in the style prop?
No. Keep reusable, known-ahead styles in CSS; reserve inline styles for values that depend on JavaScript data.


