ClassNames do not match server explanation

Viewed 32

Im using Next JS and styled components and trying to understand why this error happens. I know how to fix it and for those looking for an answer here:

Create a .babelrc file at the root and simply add this to it
{
  "presets": ["next/babel"],
  "plugins": [
    [
      "styled-components",
      { "ssr": true, "displayName": true, "preprocess": false }
    ]
  ]
}

Why does this happen though? The styles always work on first load but after that it stops working. Whats going on here?

1 Answers

The answer is here

Basically you need to add custom Document to your Next.js app and configure it to work with styled components.

Solution: create _document.(js/ts/jsx/tsx) in your pages folder and inside put this:

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

Source

Related