Styling React Using CSS

🎨 Styling React Using CSS (Complete Guide)

React gives multiple ways to apply styles to components. You can choose based on preference, project size, or structure.


✅ 1. Inline Styling

You can apply styles directly inside the component using a style object.

function App() {
const style = {
color: "blue",
backgroundColor: "lightgray",
padding: "10px",
fontSize: "20px",
};

return <h2 style={style}>Hello React!</h2>;
}

export default App;

OR inline directly:

<h2 style={{ color: "red", fontSize: "30px" }}>Inline Styled Text</h2>

Note: Inline style uses camelCase instead of CSS - syntax.


✅ 2. External CSS File

Create a CSS file:

📄 App.css

.title {
color: green;
font-size: 25px;
font-weight: bold;
}

Use it in React component:

import "./App.css";

function App() {
return <h2 className="title">Styled Using External CSS</h2>;
}

export default App;


✅ 3. CSS Modules (Recommended for Large Projects)

CSS Modules prevent class name conflicts and apply style only to the component where it’s imported.

📄 Button.module.css

.btn {
background-color: purple;
color: white;
padding: 10px;
border-radius: 5px;
}

Use it in a component:

import styles from "./Button.module.css";

function Button() {
return <button className={styles.btn}>Click Me</button>;
}

export default Button;


✅ 4. Styled Components (CSS-in-JS)

You need to install first:

npm install styled-components

Then use it:

import styled from "styled-components";

const Button = styled.button
background: orange;
color: white;
padding: 10px;
border-radius: 4px;
font-size: 18px;
;

export default function App() {
return <Button>Styled Component Button</Button>;
}


✅ 5. Tailwind CSS (Utility CSS Framework)

Install Tailwind and use utility classes:

function App() {
return <h2 className="text-xl font-bold text-blue-600">Hello Tailwind</h2>;
}

export default App;


🎯 Summary Table

Method Best For Pros Cons
Inline CSS Small components Quick & easy No hover, no pseudo selectors
External CSS General styling Simple & familiar Class name conflicts possible
CSS Modules Medium/Large Apps No class name conflict Slightly more setup
Styled Components Dynamic styling Reusable + conditional styling Requires library
Tailwind CSS Modern UI Fast, utility-first Learning curve

📌 Bonus: Conditional Styling Example

function Status({ isActive }) {
return (
<p style={{ color: isActive ? "green" : "red" }}>
{isActive ? "Active" : "Inactive"}
</p>
);
}

export default Status;


🎉 Now You Know:

  • How to style React using inline, external CSS, modules, styled components, and frameworks.

You may also like...