DEV Community

Cover image for Nextjs + typescript +styled-components

Nextjs + typescript +styled-components

Renan Aguiar on June 02, 2020

Summary 1 - Add Typescript 2 - Install styled-components 3 - Apply globalStyle 4 - Bonus 1 - Absolute imports 5 - Bonus 2 - SSR with sty...
Collapse
 
nikodermus profile image
Nicolás M. Pardo • Edited

If you are using strict TypeScript as I am, this is _document.tsx with all types included:

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();
    }
  }
}

Enter fullscreen mode Exit fullscreen mode
Collapse
 
alpfilho profile image
Alfredo Peres

thank you

Collapse
 
romulloleal profile image
Romullo Leal

I have been looking for this. Thank you my friend.

Collapse
 
nikodermus profile image
Nicolás M. Pardo

If you are using string TypeScript as I am, this is _document.tsx with all types included:

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();
    }
  }
}

Enter fullscreen mode Exit fullscreen mode
Collapse
 
ging3rmint profile image
Nate

This was super helpful but i keep getting JSX.element type error at

  return {
    ...initialProps,
    styles: (
      <>
        {initialProps.styles}
        {sheet.getStyleElement()}
      </>
    ),
  };
Enter fullscreen mode Exit fullscreen mode

is there any way to fix this?

Collapse
 
popchairat profile image
Chairat Ko

Chang from styles:(), to styles:[],

Thread Thread
 
nosovandrew profile image
Andrew Nosov

You've saved my time! Thanks!!!

Collapse
 
simonolsen profile image
Simon Olsen

Fantastic walkthrough! Your GlobalStyle setup is much better than the <style jsx global> you get OOTB with Next.js.

I was hoping for a bit more TypeScript config. I'm trying to apply some types to my styled-components. I followed the API reference for Typescript on the styled-components website but I couldn't get it working with my Next.js site. When I tried to apply some props from a DefaultTheme, example

color: ${props => props.theme.colors.main};
Enter fullscreen mode Exit fullscreen mode

I kept getting...

TypeError: Cannot read property 'main' of undefined
Enter fullscreen mode Exit fullscreen mode

I checked your example but there is no TypeScript checking in there.

Have you had any success with adding types to styled-components?

Collapse
 
rffaguiar profile image
Renan Aguiar

Hi Simon! I'm glad you liked it!
Sorry about the really long delay. I didn't receive a notification.

Did you solve the problem? I never tried to use types on my styles because they have a very dynamic nature, each one is so different from the other that I find counterproductive to create types for them.

About your error: you're trying to get a property main from another one that doesn't exist in the context, which is colors. Have you imported and set the colors property?

Collapse
 
keyes343 profile image
keyes343

Include a module file for themes, for styled components, at the root of your project. I found this solution on stackoverflow somewhere recently.

Collapse
 
farynaio profile image
Adam Faryna • Edited

Isn't:

  html {
    box-sizing: border-box;
  }

  *,
  *::before,
  *::after {
    box-sizing: inherit;
  }
Enter fullscreen mode Exit fullscreen mode

should be simply write as:

* {
  box-sizing: border-box;
}
Enter fullscreen mode Exit fullscreen mode

?

Collapse
 
8kigai profile image
8kigai
Collapse
 
clemoh profile image
Clement Oh

This was super helpful. Thank you! Was getting a SSR component className did not match error when using styled components. This setup fixed it for me.