Styling Components via CSS
React doesn’t prescribe a particular solution for styling components. A good starting point is to define styles in a separate *.css file and refer to the CSS class in JSX via the className attribute. This works the same way as the HTML class attribute.
If your project uses Vite or another modern build tool, you can import CSS directly from your JavaScript files — the build tool handles bundling the styles for you.
Avatar.css
.avatar {
border-radius: 50%;
}
Avatar.js
import './Avatar.css';
export default function Avatar() {
return <img className="avatar" alt="User avatar" />;
}
Beyond this, there are other options for styling components:
-
Inline Styles. You can pass a JavaScript object to the
styleproperty, in which case, common style names are converted tocamelCasefor the literal form. This is most often used to add dynamically-computed styles at render time. Example:// Result style: '10%' <div style={{ height: '10%' }}> Hello World! </div>
-
CSS modules. CSS modules allow locally scoped CSS files by automatically generating unique class names that combine the file name, the original class name, and a content hash. This is supported natively in Vite for files with the
.module.cssextension. -
CSS-in-JS. This refers to a pattern where CSS is composed using JavaScript instead of defined in external files. Third-party libraries such as styled-components and Emotion let you declare styles alongside your React components. Each library generates a unique class name for the styles you define, so they apply only to the components using them and won’t collide with styles elsewhere in the page.
As you progress in your journey you may mix & match different solutions, depending on the scope for the style. Eg: Global styles for theming the app with local scoped styles for components only.