0
0
NextjsHow-ToBeginner · 4 min read

How to Use Styled Components in Next.js: Simple Guide

To use styled-components in Next.js, first install it with npm install styled-components and npm install --save-dev babel-plugin-styled-components. Then, create styled components using the styled function and use them inside your Next.js pages or components for scoped CSS styling.
📐

Syntax

The basic syntax uses the styled function to create a styled React component. You write CSS inside backticks after the HTML element or component you want to style.

  • styled.element: The HTML tag or React component to style.
  • Template literal: CSS rules inside backticks ``.
  • Styled component: A React component with styles applied.
javascript
import styled from 'styled-components';

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

export default function MyComponent() {
  return <Button>Click me</Button>;
}
Output
A blue button with white text labeled 'Click me' appears on the page.
💻

Example

This example shows a Next.js page using styled-components to style a heading and a button. It demonstrates scoped CSS that only affects these components.

javascript
import styled from 'styled-components';

const Title = styled.h1`
  color: darkgreen;
  font-size: 2.5rem;
  text-align: center;
  margin-top: 2rem;
`;

const Button = styled.button`
  background-color: darkgreen;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1rem;

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

export default function Home() {
  return (
    <main>
      <Title>Welcome to Styled Components in Next.js</Title>
      <Button>Press me</Button>
    </main>
  );
}
Output
A centered dark green heading and a dark green button with white text appear. The button changes to a lighter green on hover.
⚠️

Common Pitfalls

  • Not installing styled-components or its Babel plugin causes errors.
  • For server-side rendering in Next.js, you must configure a custom _document.js to avoid style flickering.
  • Using global CSS inside styled components is not automatic; use createGlobalStyle for global styles.
  • For TypeScript, install @types/styled-components for type support.
javascript
/* Wrong: Using styled-components without _document.js setup causes styles to flash on page load */

// Right: Create pages/_document.js with styled-components SSR setup

import Document from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const sheet = new ServerStyleSheet();
    const originalRenderPage = ctx.renderPage;

    try {
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: App => props => sheet.collectStyles(<App {...props} />),
        });

      const initialProps = await Document.getInitialProps(ctx);
      return {
        ...initialProps,
        styles: (
          <>
            {initialProps.styles}
            {sheet.getStyleElement()}
          </>
        ),
      };
    } finally {
      sheet.seal();
    }
  }
}
📊

Quick Reference

ConceptDescriptionExample
Install packageAdd styled-components to your projectnpm install styled-components
Create styled componentUse styled.element with CSSconst Btn = styled.button`color: red;`
Use in componentRender styled component like normal ReactClick
Server-side setupConfigure _document.js for SSRUse ServerStyleSheet from styled-components
Global stylesUse createGlobalStyle for global CSSconst GlobalStyle = createGlobalStyle`body { margin: 0; }`

Key Takeaways

Install styled-components and its Babel plugin before using in Next.js.
Create styled components with the styled function and template literals.
Configure a custom _document.js for proper server-side rendering of styles.
Use createGlobalStyle for global CSS, not inside styled components.
Styled components provide scoped, reusable CSS inside React components.