Working with styled-components in the Next.js

Styled-components is a popular CSS-in-JS library that allows you to write component-based styling in your React projects. When combined with the capabilities of Next.js, the result is a powerful…

image

Styled-components is a popular CSS-in-JS library that allows you to write component-based styling in your React projects. When combined with the capabilities of Next.js, the result is a powerful toolset for creating dynamic and visually appealing web applications. In this blog post, we will explore how to work with styled-components in Next.js and take a look at some best practices for integrating them into your projects.

You must use the following command to install the package.

#yarn
yarn add styled-components

#npm
npm install styled-components

You can easily use it as follows.

import styled from "styled-components";

const Title = styled.h1`
  color: red;
`;

export default () => (
  <div>
    <Title>My First Next.js Page</Title>
  </div>
);

But when you want to use it inside the Next js, you may run into some problems that you may not understand why it acts like this. For example, when you refresh the page, some of the elements you created with the styled component may not be rendered correctly and may be empty. To solve this problem, you must proceed as follows.

Add babel plugin and .babelrc file

You must first install the following package.

yarn add -D babel-plugin-styled-components

Create a file called .babelrc in the project root path. You can write this command in your terminal.

touch .babelrc

The contents of this file should look like this:

{
  "presets": ["next/babel"],
  "plugins": [
    [
      "styled-components",
      {
        "ssr": true,
        "displayName": true,
        "preprocess": false
      }
    ]
  ]
}

If you used create-react-app, it is better to create a _document file that replaces your next document.

import Document, { Head, Main, NextScript } from "next/document";
// Import styled components ServerStyleSheet
import { ServerStyleSheet } from "styled-components";
export default class MyDocument extends Document {
  static getInitialProps({ renderPage }) {
    // Step 1: Create an instance of ServerStyleSheet
    const sheet = new ServerStyleSheet();
    // Step 2: Retrieve styles from components in the page
    const page = renderPage(
      (App) => (props) => sheet.collectStyles(<App {...props} />)
    );
    // Step 3: Extract the styles as <style> tags
    const styleTags = sheet.getStyleElement();
    // Step 4: Pass styleTags as a prop
    return { ...page, styleTags };
  }
  render() {
    return (
      <html>
        <Head>
          <title>My page</title>
          {/* Step 5: Output the styles in the head  */}
          {this.props.styleTags}
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    );
  }
}

Done, I hope this post is useful for you.

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics