How to use Styled-Components on NextJs and Typescript

Said BADAOUI
2 min readJan 6, 2021
NextJs + styled-components + typescript

Do you want to use styled-components on your NextJs project? Here the steps you need to do:

1. Add styled-components

if you use npm, run

npm install styled-componentsnpm install @types/styled-components

or if you use yarn, run

yarn add styled-componentsyarn add @types/styled-components

2. Add styled-component babel plugin

yarn add --dev babel-plugin-styled-components

3. Create or update.babelrc file with the following code

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

4. Create or updatepages/_document.tsx file with the following code

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

--

--

Said BADAOUI

Full-stack developer & passionate blogger, using technology to bring ideas to life and sharing knowledge through writing. Constantly learning & improving skills