Styling in React
In React, there are several ways to apply styles to components:
1. Using Global Styles (in HTML)
You can define styles inside a <style>
tag in the <head>
of your index.html
file. This is the traditional way of styling, but it is not recommended in React.
2. Using External CSS Files
You can write styles in a separate .css
file and import it into your component.
Example (styles.css
):
.heading {
color: blue;
font-size: 24px;
}
Importing and Using in React (Component.js
):
import "./styles.css"; // Import the CSS file
function App() {
return <h1 className="heading">Hello, World!</h1>;
}
- You should import the CSS file in the same file where you define the component. This keeps styles scoped to the component and makes the project more organized.
- If the CSS file contains global styles (e.g., resetting margins, font styles, or general layout), then it should be imported in
App.js
orindex.js
.
3. Using Inline Styles (style={{}}
)
React allows inline styles using the style
attribute, but instead of a regular CSS string, it takes an object.
Rules for inline styles:
- CSS properties are written in camelCase (e.g.,
background-color
becomesbackgroundColor
). - Values are written as strings or numbers (without
px
for unitless values likelineHeight
). - Useful for dynamic styles but not recommended for large projects because it makes components harder to read.
Example:
function App() {
return <h1 style={{ color: "blue", fontSize: "24px" }}>Hello, World!</h1>;
}
4. Using JavaScript Style Objects
Instead of defining styles directly inside JSX, you can create a style object inside your component and pass it to the style
attribute.
Example:
function App() {
const headingStyle = {
color: "blue",
fontSize: "24px",
textAlign: "center",
};
return <h1 style={headingStyle}>Hello, World!</h1>;
}
5. CSS Modules in React
CSS Modules are a scoped styling solution in React that helps avoid style conflicts by localizing CSS to specific components.
Step 1: Create a CSS Module File
Instead of using a regular .css
file, create a .module.css
file.
Example (Button.module.css
):
.button {
background-color: blue;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
.button:hover {
background-color: darkblue;
}
Step 2: Import and Use It Inside a React Component
import React from "react";
import styles from "./Button.module.css"; // Import styles as an object
function Button() {
return <button className={styles.button}>Click Me</button>;
}
export default Button;
How It Works:
- The CSS file is imported as an object (
styles
). - Instead of using
"button"
as a class name, we use{styles.button}
. - React automatically generates a unique class name (e.g.,
Button_button__3xZy8
) to prevent conflicts.