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 starts from Create React App, you can import the CSS from the Javascript file as the build tool has already configured webpack to extend the concept of import
to go beyond JavaScript.
Avatar.css
.avatar {
border-radius: 50%;
}
Avatar.js
import React, { Component } from 'react';
import './Avatar.css'; // Tell webpack that Avatar.js uses these styles
export default function Avatar() {
return (<img className="avatar" ... />
}
Beyond this, there are other options for styling components:
Inline Styles. You can pass a JavaScript object to the style
property, in which case, common style names are converted to camelCase
for the literal form. This is most often used top add dynamically-computed styles at render time. Example:
// Result style: '10%'
<div style={{ height: '10%' }}>
Hello World!
</div>
CSS modules. CSS modules allows locally scoped CSS files by automatically creating a unique class name of the format [filename]\*[classname]\*\_[hash]
. This is supported in Create React App for files with the .module.css
extension.
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.