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 referring to the CSS class in JSX via the className attribute. This works the same way as 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. This is provided by third-party libraries, that lets you declare styles inline in your React components. The scope is hyper-local, meaning that only siblings and their children will be affected by those styles
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.