🎨10. Styling in React

Payal PorwalPayal Porwal
11 min read

Table of contents

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

FeatureDescription
Component BasedStyle is attached to components
DynamicCan use JS logic inside styles
No ConflictsNo need to worry about className conflicts
Easier ThemingGood for dark/light theme switching

🎯 Real-Life Usage

Where UsedWhy?
Modern React AppsEasy maintenance
Big TeamsNo CSS conflicts
ThemingDark/Light mode
Design SystemsReusable UI components

πŸ“š Full Summary:

Styling MethodWhen to Use?
External CSSGlobal or simple project
Inline CSSQuick dynamic styles
CSS ModulesPrivate styles per component
Styled-ComponentsDynamic 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) ?

BenefitExplanation
1. CSS-in-JSTum CSS ko JavaScript ke andar likh sakti ho
2. Component SpecificHar component ka apna style hota hai, no conflict
3. Dynamic StylingProps ke basis pe styles change kar sakte ho
4. No Global PollutionCSS sirf usi component me apply hoti hai
5. Easy MaintenanceHar component ka style uske paas hi hota hai
6. Theming SupportEasily Dark Mode / Light Mode bana sakte ho
7. Auto Unique ClassNamesCompiler khud unique className banata hai (hash ke form me)
8. Readable and OrganizedCode 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 ya yarn 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:

CheezImportant Points
NeedGlobal CSS conflicts avoid karne ke liye
BenefitsDynamic, component-specific, no conflicts
Dhyan RakhnaProps 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:

TopicDetails
Styled ComponentsCSS-in-JS styling
PropsStyle dynamically change karna
State (useState)Dark/Light mode toggle karne ke liye
Conditional StylingTheme ke basis pe styling change karna
Component-based structureReact 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 ek darkMode 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:

ConceptWhere Used
Styled ComponentsAppContainer, Card, ToggleButton, ProfileImage
useState HookDark mode toggle
PropsDynamic CSS based on darkMode
Component ReusabilityProfileCard component banaya
Conditional StylingButton 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. πŸš€

0
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! 🌟