Loading

Quipoin Menu

Learn • Practice • Grow

react / Styled Components
tutorial

Styled Components

Traditional CSS (even with modules) keeps styles in separate files. **Styled Components** takes a different approach: it lets you write actual CSS inside your JavaScript, tied directly to a component. This is known as CSS-in-JS.

What is Styled Components?

Styled Components is a library for React that allows you to create components with encapsulated styles. You write CSS using template literals, and the library generates unique class names and injects the styles into the DOM.

With styled-components, your styles become an integral part of your component. No more jumping between files to find the right CSS rule.

Installation
npm install styled-components

Basic Usage
import styled from 'styled-components';

<!-- Create a styled button component -->
const Button = styled.button`
  background: blue;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;

  &:hover {
    background: darkblue;
  }
`;

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

Adapting Based on Props

Styled components can accept props to dynamically change styles.
const Button = styled.button`
  background: ${props => props.primary ? 'green' : 'blue'};
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
`;

<!-- Usage -->
<Button>Normal</Button>
<Button primary>Primary</Button>

Extending Styles

You can create a new component based on an existing styled component and override styles.
const TomatoButton = styled(Button)`
  background: tomato;
`;

Global Styles

Styled Components also provides a `createGlobalStyle` helper for global CSS.
import { createGlobalStyle } from 'styled-components';

const GlobalStyle = createGlobalStyle`
  body {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
  }
`;

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

Two Minute Drill

  • Styled Components is a CSS-in-JS library that lets you write CSS inside JavaScript.
  • Create styled components using `styled.elementName` with template literals.
  • Styles are automatically scoped to the component no class name conflicts.
  • You can adapt styles based on props and extend existing components.
  • Great for dynamic theming and keeping styles co-located with components.

Need more clarification?

Drop us an email at career@quipoinfotech.com