Styled Components / Emotion

Subject: React

Styled Components / Emotion in React — Detailed Guide

📍 What Are Styled Components?

Styled Components is a popular CSS-in-JS library that lets you write actual CSS inside JavaScript.

  • Styles are scoped to individual components
  • You use template literals to write clean, readable CSS
  • It supports full CSS — including media queries, animations, pseudo-selectors, and dynamic styling

🧠 Emotion is an alternative CSS-in-JS library with a similar syntax and lighter runtime in large teams.


✅ Why Use Styled Components?

FeatureBenefit
Component-scoped stylesNo global class name collisions
Dynamic styling with propsStyle changes based on props/state
Full CSS supportSupports media queries, pseudo-selectors
JS + CSS togetherLess context switching, better encapsulation
Theming supportBuilt-in ThemeProvider for global themes

🛠️ Setup

🔧 Installation

📦 Emotion (Alternative)


✅ Basic Example: Styled Button


🔍 What Happens Behind the Scenes

Styled Components:

  • Generates a unique class name
  • Injects the styles into a <style> tag in your document
  • Ensures styles are scoped, not global

✅ Dynamic Styling with Props


✅ Responsive Design


✅ Nesting & Pseudo-Selectors


✅ Example: Complete Card Component


⚠️ Things to Know

ConsiderationExplanation
Bundle sizeSlightly heavier than plain CSS
DebuggingClass names are auto-generated (can be long)
SSR support✅ Fully supported (e.g., with Next.js)
ToolingWorks well with TypeScript, Jest, Storybook

📌 Summary Table

FeatureDescription
`styled.tagName``Use styled.button, styled.div, etc.
Dynamic stylingUse props inside template literals
CSS supported✅ Media queries, animations, pseudo-selectors
Scoped automaticallyNo global collisions or overrides
Librariesstyled-components, @emotion/styled

🎯 When to Use Styled Components or Emotion

Ideal ForLess Ideal For
Component-based design systemsUtility class-based projects
Dynamic, theme-based stylingRepetitive/static styles
Avoiding naming conflictsProjects using global CSS/SCSS

💡 Final Tip

For theming, use ThemeProvider from styled-components or Emotion to apply consistent styles across your app.