Styling React Components with CSS: A Comparison of Different Techniques

Explore effective methods for styling React components, comparing inline styles, CSS Modules, styled-components, and importing external CSS files. This tutorial examines their advantages and disadvantages, helping you choose the best approach for managing styles in your React projects, improving code organization, and maintainability.



Styling React Components with CSS

This guide explores various methods for styling React components, comparing their advantages and disadvantages.

1. Inline Styles

Inline styles are applied directly to components using a JavaScript object. Property names use camelCase (e.g., `backgroundColor` instead of `background-color`).

Inline Styles Example

import React from 'react';
import ReactDOM from 'react-dom/client';

function MyComponent() {
  return (
    <div style={{ color: 'blue', fontSize: '16px' }}>
      Styled Text
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<MyComponent />);
        
Output

<div style="color: blue; font-size: 16px;">Styled Text</div>
        

You can also create a style object separately:

Separate Style Object

const myStyle = { color: 'green', fontWeight: 'bold' };
return <h1 style={myStyle}>Styled Heading</h1>;
        

2. CSS Stylesheets

Create separate CSS files (e.g., `App.css`) and import them into your components. This separates styling logic from your component code, improving organization.

Importing a Stylesheet

import './App.css'; //Import the css file
        

Your CSS file (`App.css`):

App.css

.my-class {
  color: red;
  font-size: 20px;
}
        

In your component:

Component Using Stylesheet

return <h2 className="my-class">Styled Heading</h2>;
        

3. CSS Modules

CSS Modules create scoped styles. Each component gets its own isolated stylesheet, preventing naming conflicts. Use the `.module.css` extension (e.g., `styles.module.css`).

CSS Module Import

import styles from './myStyles.module.css';
return <div className={styles.myClass}>Styled Text</div>;
        

4. Styled Components

Styled-components is a library that uses tagged template literals to write actual CSS within your JavaScript. It provides many benefits, including automatic critical CSS extraction, dynamic styling, and easy maintenance.

Installation

Installation Command

npm install styled-components --save
        

Usage

Styled Components Example

import styled from 'styled-components';

const MyComponent = styled.div`
  background-color: lightblue;
  padding: 10px;
`;

// Usage in component:
return <MyComponent>Styled Content</MyComponent>;