π¨10. Styling in React

Table of contents
- 1οΈβ£ CSS in React
- 2οΈβ£ Conditional Styling
- 3οΈβ£ Styled Components (β Deep Dive)
- π― Real-Life Usage
- π Full Summary:
- π Final Tip:
- π FAQs :
- π Styled Components ki Need ( ΰ€ΰ€Όΰ€°ΰ₯ΰ€°ΰ€€ ΰ€ΰ₯ΰ€―ΰ₯ΰ€ ΰ€ͺΰ€‘ΰ€Όΰ₯ ? )
- π What are the Benefits of Styled Components (Faayde) ?
- π¦ Styled Components Use karte time Important Points (Dhyan dene layak baatein) ?
- π₯Koi Real Life Example Situation ?:
- π― Conclusion:
- π Quick Summary for Revision:
- π Mini Project Idea: "Simple Profile Card with Dark/Light Mode"
- π οΈ Tools and Topics Covered:
- β¨ Step 1: Install Styled Components
- β¨ Step 2: Project Folder Structure
- β¨ Step 3: Code likhna start karte hain!
- π Full Flow Explanation:
- π Concepts Covered in This Project:
- π Final Output (Summary)
- β Conclusion:
- π₯ Extra Tips:
1οΈβ£ CSS in React
In React, you can style your app in different ways:
1. External CSS File
Just like normal HTML websites.
Create a separate
.css
file and import it into your component.
π΅ Example:
App.css
cssCopyEdit.heading {
color: blue;
text-align: center;
}
App.js
jsxCopyEditimport React from 'react';
import './App.css';
function App() {
return <h1 className="heading">Hello World</h1>;
}
export default App;
β
When to use:
When you have global styles or reusable styles.
2. Inline CSS
Apply CSS directly inside the element using the
style
prop.In React,
style
expects an object, not a string.
π΅ Example:
jsxCopyEditfunction App() {
const myStyle = {
color: 'green',
backgroundColor: 'lightyellow',
padding: '10px'
};
return <h2 style={myStyle}>Welcome to Styling in React!</h2>;
}
β
When to use:
For dynamic styles or small quick designs.
β Important:
In inline style β properties are written in camelCase, not with hyphens.
Example:
Correct:
backgroundColor
Incorrect:
background-color
3. CSS Modules
It solves global pollution problem of CSS.
In React apps, CSS files can affect every component.
But CSS Modules make styles component-scoped.
π΅ How to create a CSS module?
Save your file with
.module.css
extension.Import it like a JavaScript object.
Button.module.css
cssCopyEdit.btn {
background-color: purple;
color: white;
padding: 10px 20px;
border-radius: 5px;
}
Button.js
jsxCopyEditimport React from 'react';
import styles from './Button.module.css';
function Button() {
return <button className={styles.btn}>Click Me</button>;
}
export default Button;
β
When to use:
When you want private styling β style only for that component.
2οΈβ£ Conditional Styling
React allows you to apply styles based on conditions, like:
π΅ Example using className
jsxCopyEditfunction App() {
const isLoggedIn = true;
return (
<h2 className={isLoggedIn ? "welcome" : "please-login"}>
{isLoggedIn ? "Welcome Back!" : "Please Login"}
</h2>
);
}
CSS:
cssCopyEdit.welcome {
color: green;
}
.please-login {
color: red;
}
π΅ Example using Inline Style
jsxCopyEditfunction App() {
const isAdmin = true;
return (
<h2 style={{ color: isAdmin ? "blue" : "gray" }}>
{isAdmin ? "Admin Panel" : "User Panel"}
</h2>
);
}
3οΈβ£ Styled Components (β Deep Dive)
Styled-components is a popular library that lets you:
Write CSS inside JS
Attach styles to specific components
Handle dynamic styling easily
π΅ Install it first:
bashCopyEditnpm install styled-components
β¨ Basic Example
jsxCopyEditimport React from 'react';
import styled from 'styled-components';
const Title = styled.h1`
color: royalblue;
text-align: center;
margin-top: 50px;
`;
function App() {
return <Title>Hello Styled Components</Title>;
}
export default App;
β Explanation:
styled.h1
β means you're creating an H1 element with custom styles.Title
is a React component you can use normally!
β¨ Styled Components with Props (Dynamic Styling)
You can change styles based on props.
jsxCopyEditconst Button = styled.button`
background: ${props => (props.primary ? "palevioletred" : "white")};
color: ${props => (props.primary ? "white" : "palevioletred")};
padding: 10px 20px;
border: 2px solid palevioletred;
border-radius: 5px;
margin: 5px;
cursor: pointer;
`;
function App() {
return (
<div style={{ textAlign: "center" }}>
<Button>Normal</Button>
<Button primary>Primary</Button>
</div>
);
}
β Explanation:
- If we pass
primary
prop, button will have different styles.
β¨ Benefits of Styled Components
Feature | Description |
Component Based | Style is attached to components |
Dynamic | Can use JS logic inside styles |
No Conflicts | No need to worry about className conflicts |
Easier Theming | Good for dark/light theme switching |
π― Real-Life Usage
Where Used | Why? |
Modern React Apps | Easy maintenance |
Big Teams | No CSS conflicts |
Theming | Dark/Light mode |
Design Systems | Reusable UI components |
π Full Summary:
Styling Method | When to Use? |
External CSS | Global or simple project |
Inline CSS | Quick dynamic styles |
CSS Modules | Private styles per component |
Styled-Components | Dynamic styling, real-world big projects |
π Final Tip:
If you're building:
Small Projects β CSS modules are enough.
Professional/Big Projects β Start using Styled Components for better scalability!
π FAQs :
π Styled Components ki Need ( ΰ€ΰ€Όΰ€°ΰ₯ΰ€°ΰ€€ ΰ€ΰ₯ΰ€―ΰ₯ΰ€ ΰ€ͺΰ€‘ΰ€Όΰ₯ ? )
React apps jab chhoti hoti hai tab simple CSS se kaam chal jata hai.
Lekin jaise-jaise app badi hoti hai ya team mein multiple developers kaam karte hain, kuch major problems aati hain:
1. CSS Class Name Conflict
Sabhi components ka CSS global hota hai.
Matlab agar
button
naam ka class alag-alag components me hai, toh unka styling conflict kar sakta hai.Ek component ka style doosre pe galti se apply ho jata hai.
π Problem: Maintenance mushkil hoti hai, bugs aate hain.
2. No Component-specific Styling
CSS ek global file hai, components se direct link nahi hota.
Agar kisi naye developer ko koi component ka style change karna ho, toh use poora CSS search karna padta hai.
π Problem: Time waste aur galti ka risk.
3. Dynamic Styling Mushkil
CSS mein normal if-else, props ke basis pe styling karna tough hai.
JS ke logic easily use nahi kar sakte CSS mein.
π Problem: Code complicated aur confusing ban jata hai.
π΅ π Styled Components isiliye laaye gaye!
Ye har component ke liye apna private CSS create karte hain, dynamic styles allow karte hain, aur JS + CSS dono ka best combination dete hain.
dete hain.
π What are the Benefits of Styled Components (Faayde) ?
Benefit | Explanation |
1. CSS-in-JS | Tum CSS ko JavaScript ke andar likh sakti ho |
2. Component Specific | Har component ka apna style hota hai, no conflict |
3. Dynamic Styling | Props ke basis pe styles change kar sakte ho |
4. No Global Pollution | CSS sirf usi component me apply hoti hai |
5. Easy Maintenance | Har component ka style uske paas hi hota hai |
6. Theming Support | Easily Dark Mode / Light Mode bana sakte ho |
7. Auto Unique ClassNames | Compiler khud unique className banata hai (hash ke form me) |
8. Readable and Organized | Code clean dikhta hai, CSS aur Component ek saath dikhte hain |
π¦ Styled Components Use karte time Important Points (Dhyan dene layak baatein) ?
1. Props Handling Sahi Se Karni Hai
- Jab dynamic style lagana ho props ke through, toh sahi tarike se
{props => }
use karna hai.
jsxCopyEditconst Button = styled.button`
background: ${props => (props.primary ? 'blue' : 'gray')};
`;
2. Component Naming Achha Rakho
Styled component ka naam meaningful hona chahiye jaise
StyledButton
,CardWrapper
,HeaderTitle
etc.Jaise coding me function aur variable ke naam achhe rakhte hain, waise hi yaha bhi.
3. Avoid Over Nesting
- Jaise normal CSS me unnecessary zyada nesting galat hai, waise hi Styled Components me bhi minimal aur clean nesting rakho.
4. Install Library Correctly
npm install styled-components
yayarn add styled-components
se install karo.Install karna compulsory hai kyunki ye external package hai.
5. Theming ka Use Samajhna
- Badi applications me dark mode, light mode ya multiple theme ka support dena ho to Styled Components ka
ThemeProvider
ka use hota hai.
(Main chaaho to ispar bhi alag detailed article bana sakti hoon!)
6. Performance ko Dhyan me Rakho
Bahut zyada chhote components ko alag alag Styled Components me mat tod do.
Logical group bana ke design karo.Har ek CSS line ke liye new styled-component banana zaroori nahi.
π₯Koi Real Life Example Situation ?:
Imagine ek badi company ka dashboard app:
Sidebar, Navbar, Cards, Buttons, Tables β sabke alag styles chahiye.
Agar normal CSS likhte, toh sidebar ke button aur card ke button ka style clash kar jaata.
Isliye Styled Components use karte hain β taaki sidebar ka button apne hi style me ho aur card ka button apne style me ho.
π― Conclusion:
β
Styled Components React apps ko scalable, maintainable aur flexible banate hain.
β
Ye professional React projects me industry standard hai.
β
Agar tum future me big real-world projects banana chahti ho, toh Styled Components ki strong command hona zaroori hai.
π Quick Summary for Revision:
Cheez | Important Points |
Need | Global CSS conflicts avoid karne ke liye |
Benefits | Dynamic, component-specific, no conflicts |
Dhyan Rakhna | Props handling, naming, avoid over-nesting |
π Mini Project Idea: "Simple Profile Card with Dark/Light Mode"
Ye project real life me kaam aa sakta hai jab tum user profile cards, team members ka showcase, ya product cards banana chahti ho.
π οΈ Tools and Topics Covered:
Topic | Details |
Styled Components | CSS-in-JS styling |
Props | Style dynamically change karna |
State (useState ) | Dark/Light mode toggle karne ke liye |
Conditional Styling | Theme ke basis pe styling change karna |
Component-based structure | React best practice follow karna |
β¨ Step 1: Install Styled Components
First, terminal me run karo:
bashCopyEditnpm install styled-components
β¨ Step 2: Project Folder Structure
luaCopyEdit/src
|-- App.js
|-- ProfileCard.js
|-- styles.js
β¨ Step 3: Code likhna start karte hain!
π /src/styles.js
(Ye file sirf styled-components ke liye hogi)
javascriptCopyEdit// styles.js
import styled from "styled-components";
// Container for entire app
export const AppContainer = styled.div`
background-color: ${(props) => (props.darkMode ? "#2c3e50" : "#ecf0f1")};
color: ${(props) => (props.darkMode ? "white" : "black")};
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
padding: 2rem;
transition: all 0.5s ease;
`;
// Card styling
export const Card = styled.div`
background: ${(props) => (props.darkMode ? "#34495e" : "#fff")};
padding: 2rem;
border-radius: 10px;
box-shadow: ${(props) => (props.darkMode
? "0px 0px 10px #000"
: "0px 0px 10px #ccc")};
width: 300px;
text-align: center;
`;
// Button for toggling dark/light mode
export const ToggleButton = styled.button`
margin-bottom: 2rem;
padding: 10px 20px;
background: ${(props) => (props.darkMode ? "#1abc9c" : "#3498db")};
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 1rem;
&:hover {
opacity: 0.8;
}
`;
// Profile Image styling
export const ProfileImage = styled.img`
width: 120px;
height: 120px;
border-radius: 50%;
margin-bottom: 1rem;
object-fit: cover;
`;
π /src/ProfileCard.js
(ProfileCard component banayenge)
javascriptCopyEdit// ProfileCard.js
import React from 'react';
import { Card, ProfileImage } from './styles';
function ProfileCard({ name, title, imgUrl, darkMode }) {
return (
<Card darkMode={darkMode}>
<ProfileImage src={imgUrl} alt="Profile" />
<h2>{name}</h2>
<p>{title}</p>
</Card>
);
}
export default ProfileCard;
π /src/App.js
(Main App file)
javascriptCopyEdit// App.js
import React, { useState } from 'react';
import ProfileCard from './ProfileCard';
import { AppContainer, ToggleButton } from './styles';
function App() {
const [darkMode, setDarkMode] = useState(false);
function toggleTheme() {
setDarkMode((prevMode) => !prevMode);
}
return (
<AppContainer darkMode={darkMode}>
<ToggleButton darkMode={darkMode} onClick={toggleTheme}>
{darkMode ? "Switch to Light Mode" : "Switch to Dark Mode"}
</ToggleButton>
<ProfileCard
name="Payal Sharma"
title="Frontend Developer"
imgUrl="https://randomuser.me/api/portraits/women/44.jpg"
darkMode={darkMode}
/>
</AppContainer>
);
}
export default App;
π Full Flow Explanation:
1. Styled Components
Alag-alag components jaise
AppContainer
,Card
,ToggleButton
,ProfileImage
banaye.Ye sare CSS ko JS ke andar likhte hain using
styled-components
.
2. Dark Mode Handling
useState
hook se ekdarkMode
boolean variable banaya.Jab button click hota hai, dark mode on/off toggle ho jata hai.
3. Props for Dynamic Styling
Har styled component me
props.darkMode
check kar rahe hain.Agar darkMode true hai to dark background, otherwise light background.
4. Responsive Layout
Card aur container center me align hai.
Responsive ke liye width fix aur padding diye hain.
(Advanced me media queries bhi styled components ke through add kar sakte ho.)
π Concepts Covered in This Project:
Concept | Where Used |
Styled Components | AppContainer , Card , ToggleButton , ProfileImage |
useState Hook | Dark mode toggle |
Props | Dynamic CSS based on darkMode |
Component Reusability | ProfileCard component banaya |
Conditional Styling | Button aur Card ke colors change |
π Final Output (Summary)
App ek beautiful profile card dikhayega.
"Switch to Dark Mode" button click karte hi pura app dark ho jayega.
Responsive, clean, real-world ready code.
β Conclusion:
Styled Components real life me styling aur theme management ko itna aasaan aur powerful banate hain!
Ye mini-project tumhe har important React + Styled-Components concept practically sikha dega.
π₯ Extra Tips:
Chaaho to isme multiple Profile Cards list bana ke, map()
laga ke multiple profiles dikhane ka feature bhi add kar sakte ho. (List + Dynamic Forms ka practice bhi ho jayega.)
π Stay Connected
If you found this article helpful and want to receive more such beginner-friendly and industry-relevant React notes, tutorials, and project ideas β
π© Subscribe to our newsletter by entering your email below.
And if you're someone who wants to prepare for tech interviews while having a little fun and entertainment,
π₯ Donβt forget to subscribe to my YouTube channel β Knowledge Factory 22 β for regular content on tech concepts, career tips, and coding insights!
Stay curious. Keep building. π
Subscribe to my newsletter
Read articles from Payal Porwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Payal Porwal
Payal Porwal
Hi there, tech enthusiasts! I'm a passionate Software Developer driven by a love for continuous learning and innovation. I thrive on exploring new tools and technologies, pushing boundaries, and finding creative solutions to complex problems. What You'll Find Here On my Hashnode blog, I share: π In-depth explorations of emerging technologies π‘ Practical tutorials and how-to guides π§Insights on software development best practices πReviews of the latest tools and frameworks π‘ Personal experiences from real-world projects. Join me as we bridge imagination and implementation in the tech world. Whether you're a seasoned pro or just starting out, there's always something new to discover! Letβs connect and grow together! π