How to setup NextJs and Typescript with Styled-component
Tags: styledcomponents, react, nextjs, frontend
Published: 2022-12-13 14:19:20

---
title: How to setup NextJs and Typescript with Styled-component
published: true
description: Styled-components makes it simple to style your components with CSS by using javascript code. It also makes it simple to design a theme for your entire project. 
tags: #styledcomponents #react #nextjs #frontend
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2022-11-27 10:53 +0000
---


## Introduction
Follow this guide to setup style components in react components 

Styled-components makes it simple to style your components with CSS by using javascript code. It also makes it simple to design a theme for your entire project. 

[Learn More](https://styled-components.com/docs)

## Table Of Content
- [Create Nextjs Project](#create-nextjs-project)
- [Add Styled-components Library](#add-styled-components-library)
- [[optional] Styled Components Babel Plugin](#optional-styled-components-babel-plugin)
- [[optional] SSR Stylesheet Rehydration](#optional-ssr-stylesheet-rehydration)
- [[optional] Absolute imports & Module Path Aliases](#optional-absolute-imports--module-path-aliases)

## Create Nextjs Project
Create Nextjs easily by using `create-next-app` by running the command below replace <project> with your project name

`yarn create next-app <project> --ts`

or if you need eslint run the command below instead, replace <project> with your project name
  
`yarn create next-app <project> --ts --eslint`

[learn more on getting started with Nuxtjs](https://nextjs.org/learn/basics/create-nextjs-app)

## Add Styled-components Library
In your project root directory run the command below to add styled-components library

`yarn add styled-components && yarn add -D @types/styled-components` 

Use `globalStyle`, to share styles across all of your pages, for example if you would like;
- Setting a font-family for all your typography
- Setting the background color on every page

![layout directory](https://res.cloudinary.com/dtflhfxow/image/upload/c_scale,w_317/v1669324144/Screenshot_2022-11-25_at_12.45.03_AM_c7vjcu.png)

create a folder `/layout` with file `Default.tsx` inside, then add the following:
```
import { createGlobalStyle } from "styled-components";

export const GlobalStyle = createGlobalStyle`
  html,
  body {
    padding: 0;
    margin: 0;
    font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
      Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
    }
    
    a {
      color: inherit;
      text-decoration: none;
    }
    
    * {
      box-sizing: border-box;
    }
  }
  
  p {
    color: red;
  }

  // anything else you would like to include
`;

export function LayoutDefault({ children }: { children: any }) {
  return (
    <>
      <GlobalStyle />
      {children}
    </>
  );
}
```

Inside the GlobalStyle variable is where you define all your global styles.
  In this example, we simply set the font family, link color, and paragraph color for every page LayoutDefault is used

This isn’t going to apply the styles to the project yet.

Now we need to use that file to apply the global styles to the project.

Modify `index.tsx` file in the `/pages` folder, import the LayoutDefault component and wrap the returned React element in the Home function with LayoutDefault.
```
import styled from "styled-components";
import LayoutDefault from "../layout/Default";

const StyledHeading = styled.h1`
  color: pink;
`;

export default function Home() {
  return (
    <LayoutDefault>
      <StyledHeading>Title</StyledHeading>
      <p>hello</p>
    </LayoutDefault>
  );
};
```
[learn more about Layouts](https://nextjs.org/docs/basic-features/layouts)

## [optional] Styled Components Babel Plugin
You need to add the babel styled components plugin, if you want any of the following features 
- Smaller bundles
- Server-side rendering compatibility
- Better debugging
- Minification
- Dead code elimination
[learn more about](https://styled-components.com/docs/tooling#babel-plugin)

`yarn add -D babel-plugin-styled-components`

Create a file `.babelrc` at the root of your project with the following:
   
```
{
  "presets": ["next/babel"],
  "plugins": [["styled-components", { "ssr": true }]]
}
```

## [optional] SSR Stylesheet Rehydration
ServerStyleSheet is created by Styled-Components. Any styles located in any of the components inside of our <App /> are retrieved from this stylesheet. Later, this is passed into our HTML template.

create file `_document.tsx` in the `/pages` directory and add the following
```
import Document, { DocumentContext, DocumentInitialProps } from 'next/document';
import { ServerStyleSheet } from 'styled-components';

export default class MyDocument extends Document {
  static async getInitialProps(
    ctx: DocumentContext
  ): Promise<DocumentInitialProps> {
    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();
    }
  }
}
```

## [optional] Absolute imports & Module Path Aliases
If you've ever imported deep components and they appear with a module path alias like this:../../../../DeepComponent, with Module Path Alias you can import them like this instead `components/path/DeepComponent`
  
[learn about absolut imports and module path aliases](https://nextjs.org/docs/advanced-features/module-path-aliases)

```
{
  "compilerOptions": {
    "baseUrl": "."
  }
}
```

Now in `/pages/index.tsx` you can do this instead of that:
```
// This
import LayoutDefault from "layout/Default";

// That
import LayoutDefault from "../layout/Default";
```