Using Emotion or Styled-Components for CSS-in-JS in React

By Maulik Paghdal

22 Dec, 2024

Using Emotion or Styled-Components for CSS-in-JS in React

CSS-in-JS libraries like Emotion and Styled-Components have transformed the way developers style React components. These tools allow you to define styles directly within your JavaScript files, making your components more modular, dynamic, and maintainable.

In this guide, we’ll dive into Emotion and Styled-Components, covering their features, differences, and best practices to help you decide which fits your project better.

What is CSS-in-JS?

CSS-in-JS is a styling approach where CSS is written as JavaScript. Instead of managing styles in separate .css files, you can define them within your components. Libraries like Emotion and Styled-Components offer robust tools for applying dynamic styles, handling scoped styles, and optimizing performance.

Why Use CSS-in-JS?

  1. Scoped Styling: Avoids class name conflicts by scoping styles to components.
  2. Dynamic Styling: Easily apply styles based on component props or states.
  3. Enhanced Productivity: No need to switch between JavaScript and CSS files.
  4. Theming Support: Easily manage and apply themes across your application.

What is Styled-Components?

Styled-Components is a popular CSS-in-JS library that uses tagged template literals to style components. It allows you to write actual CSS syntax inside your JavaScript, making it intuitive for developers familiar with CSS.

Features of Styled-Components

  1. Tagged Template Literals: Use standard CSS syntax in your JavaScript files.
import styled from 'styled-components';

const Button = styled.button`
    background-color: blue;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 5px;
    cursor: pointer;

    &:hover {
    background-color: darkblue;
    }
`;

export default Button;
  1. Dynamic Styling: Apply styles based on component props.
const Button = styled.button`
    background-color: ${(props) => (props.primary ? 'blue' : 'gray')};
    color: white;
`;
  1. Theming: Easily manage global themes using the ThemeProvider.
import { ThemeProvider } from 'styled-components';

const theme = {
    primary: 'blue',
    secondary: 'gray',
};

<ThemeProvider theme={theme}>
    <App />
</ThemeProvider>;

What is Emotion?

Emotion is another powerful CSS-in-JS library offering both styled components and the flexibility to define styles as objects. Emotion provides more options for styling, making it versatile for various use cases.

Features of Emotion

  1. Styled Components: Similar to Styled-Components, Emotion supports styled API.
import styled from '@emotion/styled';

const Button = styled.button`
    background-color: blue;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 5px;
    cursor: pointer;

    &:hover {
    background-color: darkblue;
    }
`;
  1. CSS Prop: Use the css prop for inline dynamic styles.
import { css } from '@emotion/react';

const style = css`
    background-color: blue;
    color: white;
    padding: 10px 20px;
`;

const Button = () => <button css={style}>Click Me</button>;
  1. Global Styles: Define global styles using Emotion's Global component.
import { Global, css } from '@emotion/react';

<Global
    styles={css`
    body {
        margin: 0;
        font-family: Arial, sans-serif;
    }
    `}
/>;

Styled-Components vs. Emotion: A Comparison

FeatureStyled-ComponentsEmotion
Styling APIStyled API onlyStyled API and css prop
PerformanceOptimized for styled usageSlightly faster with css prop
Theming SupportExcellentExcellent
Learning CurveEasier for CSS developersSlightly steeper
Community SupportLarge communityGrowing rapidly

Best Practices for CSS-in-JS

  1. Keep Styles Modular: Define styles for individual components to ensure reusability and maintainability.
  2. Use Theming for Consistency: Centralize your colors, fonts, and sizes in a theme object to ensure consistent design.
  3. Avoid Overusing Inline Styles: While dynamic styles are powerful, avoid cluttering your components with excessive inline logic.
  4. Leverage Global Styles Sparingly: Use global styles only for base resets and universal elements like body or html.

When to Use Emotion or Styled-Components?

Choose Styled-Components if:

  • You prefer a simple, CSS-like syntax.
  • You want to focus on styled components exclusively.

Choose Emotion if:

  • You need flexibility with multiple APIs (styled and css prop).
  • You want more control over performance optimizations.

Example Project: Themed Buttons with Styled-Components

Step 1: Install Styled-Components

npm install styled-components

Step 2: Define a Theme

import { ThemeProvider } from 'styled-components';

const theme = {
  primary: 'blue',
  secondary: 'gray',
};

export default theme;

Step 3: Create Styled Components

import styled from 'styled-components';

const Button = styled.button`
  background-color: ${(props) => props.theme.primary};
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;

  &:hover {
    background-color: darkblue;
  }
`;

export default Button;

Step 4: Apply Theme in Your App

import React from 'react';
import { ThemeProvider } from 'styled-components';
import theme from './theme';
import Button from './Button';

const App = () => (
  <ThemeProvider theme={theme}>
    <Button>Click Me</Button>
  </ThemeProvider>
);

export default App;

Conclusion

Both Emotion and Styled-Components are excellent tools for managing CSS-in-JS in React applications. Your choice depends on your specific needs—whether it’s simplicity, flexibility, or performance.

Experiment with both to determine which library aligns best with your workflow and project requirements.

Topics Covered