How to Apply Styles in React (Inline, CSS Modules, Styled-Components)
Styling in React can be done in multiple ways depending on the project's needs. Here's a breakdown of the three popular approaches:
1. Inline Styling
- What it is: Applying styles directly to elements using the
style
attribute. - Syntax: Styles are passed as a JavaScript object with camelCase property names.
function InlineExample() { return ( <div style={{ backgroundColor: 'lightblue', padding: '20px', color: 'white' }}> This is styled using inline styles! </div> ); }
- Pros:
- Quick and simple for small components.
- No external CSS file required.
- Cons:
- No support for pseudo-classes (
:hover
,:active
) or media queries. - Can lead to cluttered code if overused.
- No support for pseudo-classes (
2. CSS Modules
- What it is: Scoped CSS files where class names are locally scoped by default.
- Syntax: Create a CSS file with a
.module.css
extension and import it into your component.
Example:
Button.module.css
.button { background-color: teal; color: white; padding: 10px 20px; border: none; border-radius: 5px; }
Component:
import styles from './Button.module.css'; function CSSModuleExample() { return ( <button className={styles.button}> Click Me </button> ); }
- Pros:
- No risk of global CSS conflicts.
- Easy to maintain and modularize styles.
- Cons:
- Requires build setup (default in Create React App).
3. Styled-Components (CSS-in-JS)
- What it is: A popular library that lets you write actual CSS code inside JavaScript files using tagged template literals.
- Syntax: Install the library (
npm install styled-components
) and create styled components.
Example:
import styled from 'styled-components'; const StyledButton = styled.button` background-color: purple; color: white; padding: 10px 20px; border: none; border-radius: 5px; `; function StyledComponentExample() { return <StyledButton>Styled Button</StyledButton>; }
- Pros:
- Dynamic styling based on props.
- Fully scoped styles, no conflicts.
- Can use media queries and nesting directly.
- Cons:
- Adds an extra dependency.
- Slight runtime overhead.
Conclusion
Method | Best For |
---|---|
Inline Styles | Quick, simple styles for small components |
CSS Modules | Medium to large apps needing modular styling |
Styled-Components | Complex UIs needing dynamic, scoped styling |
Choosing the right styling method depends on your project’s complexity and team preferences!