ways to style the react apps
Styling React applications can be approached in several ways, each with its own advantages depending on the project's needs and preferences. Here are some common methods for styling React apps:
1. CSS Modules
Description: CSS Modules are CSS files where all class and animation names are scoped locally by default. This means that class names are automatically hashed and scoped locally to the component, preventing style conflicts.
Example:
// Button.module.css
.button {
background-color: #007bff;
color: white;
border: none;
padding: 10px 20px;
cursor: pointer;
}
// Button.js
import styles from './Button.module.css';
const Button = () => {
return <button className={styles.button}>Click me</button>;
};
Advantages:
- Encapsulated styles prevent global scope pollution.
- Familiar CSS syntax and tooling.
2. Styled Components
Description: Styled Components allows you to write actual CSS to style components. It utilizes tagged template literals to style your components, and each styled component renders a unique class name.
Example:
import styled from 'styled-components';
const Button = styled.button`
background-color: #007bff;
color: white;
border: none;
padding: 10px 20px;
cursor: pointer;
`;
const App = () => {
return <Button>Click me</Button>;
};
Advantages:
- Write CSS directly in your JavaScript files, making styles more cohesive with components.
- Dynamic styling based on props.
3. CSS-in-JS Libraries (e.g., Emotion, JSS)
Description: CSS-in-JS libraries allow you to write CSS styles within JavaScript. They typically provide features like scoped styles, dynamic styling based on props, and easy integration with React components.
Example (using Emotion):
/** @jsxImportSource @emotion/react */
import { css } from '@emotion/react';
const buttonStyle = css`
background-color: #007bff;
color: white;
border: none;
padding: 10px 20px;
cursor: pointer;
`;
const Button = () => {
return <button css={buttonStyle}>Click me</button>;
};
Advantages:
- Encapsulated styles prevent global scope pollution.
- Supports dynamic styles and theming.
4. Framework-Based Styling (e.g., Bootstrap, Material-UI, tailwind CSS, Shadcn)
Description: Use of UI component libraries like Bootstrap or Material-UI, which provide pre-styled components and grids that can be easily integrated into React applications.
Example (using Material-UI):
import { Button } from '@mui/material';
const App = () => {
return <Button variant="contained" color="primary">Click me</Button>;
};
Advantages:
- Rapid prototyping with pre-styled components.
- Consistent design across applications.