SmartCodingTips

🎭 Emotion – CSS-in-JS Library

Emotion is a performant and flexible CSS-in-JS library for writing styles with JavaScript. It supports both styled-components-style and className-based approaches.


📦 1. Installation

For React:


npm install @emotion/react @emotion/styled

🧱 2. Using @emotion/styled


import styled from '@emotion/styled';

const Button = styled.button`
  background-color: #2563eb;
  color: white;
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-weight: bold;

  &:hover {
    background-color: #1e40af;
  }
`;

function App() {
  return <Button>Click Me</Button>;
}

🎨 3. Using css prop

This lets you apply styles directly to elements:


/** @jsxImportSource @emotion/react */
import { css } from '@emotion/react';

const style = css`
  color: white;
  background: #22c55e;
  padding: 10px;
`;

function Alert() {
  return <div css={style}>Success!</div>;
}

🧠 4. Theming Support


import { ThemeProvider } from '@emotion/react';

const theme = {
  colors: {
    primary: '#9333ea',
  },
};

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

✅ 5. Why Use Emotion?

  • Powerful CSS-in-JS syntax
  • Supports theming and dynamic styles
  • Works well with TypeScript
  • Flexible — use styled or css prop