How to Add CSS in React: Simple Methods Explained
In React, you can add CSS by importing a
.css file, using inline styles with the style attribute, or applying CSS modules for scoped styles. Each method lets you style components effectively depending on your project needs.Syntax
There are three common ways to add CSS in React:
- Import CSS file: Import a
.cssfile and use class names withclassName. - Inline styles: Use the
styleattribute with a JavaScript object for styles. - CSS Modules: Import styles as a module for scoped class names.
jsx
/* Import CSS file */ import './App.css'; function Component() { return <div className="container">Hello</div>; } /* Inline styles */ function ComponentInline() { return <div style={{ color: 'red', fontSize: '20px' }}>Hello</div>; } /* CSS Modules */ import styles from './App.module.css'; function ComponentModule() { return <div className={styles.container}>Hello</div>; }
Example
This example shows how to use an imported CSS file and inline styles together in a React component.
jsx
import React from 'react'; import './App.css'; function Greeting() { const inlineStyle = { color: 'blue', fontWeight: 'bold' }; return ( <div> <h1 className="title">Welcome to React</h1> <p style={inlineStyle}>This text is styled with inline CSS.</p> </div> ); } export default Greeting;
Output
A heading with styles from App.css and a blue bold paragraph below it.
Common Pitfalls
Common mistakes when adding CSS in React include:
- Using
classinstead ofclassNamefor CSS classes. - Writing inline styles with hyphenated CSS properties instead of camelCase (e.g.,
backgroundColornotbackground-color). - Not importing CSS files correctly or forgetting to configure CSS modules.
jsx
/* Wrong: Using class instead of className */ function Wrong() { return <div className="container">Oops</div>; } /* Right: Use className */ function Right() { return <div className="container">Correct</div>; } /* Wrong: Inline style with hyphen */ function WrongStyle() { return <div style={{ 'background-color': 'yellow' }}>Oops</div>; } /* Right: Inline style with camelCase */ function RightStyle() { return <div style={{ backgroundColor: 'yellow' }}>Correct</div>; }
Quick Reference
| Method | Usage | Notes |
|---|---|---|
| Import CSS file | import './App.css'; and use className | Global styles, simple to use |
| Inline styles | style={{ color: 'red' }} | Good for dynamic styles, camelCase keys |
| CSS Modules | import styles from './App.module.css'; use className={styles.class} | Scoped styles, avoids conflicts |
Key Takeaways
Use
className to apply CSS classes in React components.Inline styles require JavaScript objects with camelCase property names.
Import CSS files for global styles or CSS modules for scoped styles.
Avoid using
class attribute or hyphenated style keys in React.Choose the CSS method that fits your project size and style needs.