Next.Js React app with styled components. Warning: Prop `className` did not match. Server: "x" Client: "y"
Asked Answered
S

5

14

In my NextJS React app when i change something in the code, the HMR works and shows the correct update but if I refresh the page, this error comes up again. This happens on dev mode. Noticed where are a lot of topics with this error, tried all day different configuration setups with no effort.

Please help me to get rid of the error.

Error:

Warning: Prop className did not match. Server: "sc-cBoprd hjrjKw" Client: "sc-iCoHVE daxLeG"

Using "babel-plugin-styled-components": "1.11.1"

Files that can be related to the issue:

_App.tsx

function MyApp({ Component, pageProps, mainController }) {
  return (
    <ConfigurationProvider configuration={configuration}>
        <ThemeProvider theme={mainController.getTheme()}>
          <Normalize />
          <Font />
          <Component {...pageProps} controller={mainController} />
        </ThemeProvider>
    </ConfigurationProvider>
  );
}

export default appControllerContext(MyApp);

_document.tsx

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

.babelrc

{
  "presets": [
    "next/babel"
  ],
  "plugins": [
    [
      "babel-plugin-styled-components",
      {
        "ssr": true,
        "displayName": true,
        "preprocess": false
      }
    ]
  ]
}
Socinian answered 13/10, 2020 at 13:38 Comment(1)
Error you are receiving is caused by having client side only code that is also rendered on server. Can you post the entire tree? ConfigurationProvider, Normalize, Font and page contents where you receive the error.Pelvic
A
5

This error means that something on the server is different from the Client. This can happen if the client does a re-render.

Styled Components use a random id on React elements, and when these elements get re-rendered they get a new random id on the client.

So the solution here is to get the styling exclusively from the server.

from the docs:

Basically you need to add a custom pages/_document.js (if you don't have one). Then copy the logic for styled-components to inject the server side rendered styles into the <head>

To solve this issue is you need something like this in your Document component:

export default class MyDocument extends Document {
  static getInitialProps({ renderPage }) {
    const sheet = new ServerStyleSheet();
    const page = renderPage((App) => (props) =>
      sheet.collectStyles(<App {...props} />)
    );
    const styleTags = sheet.getStyleElement();
    return { ...page, styleTags };
  }
  ...
  render() { ..}
}

The final step (if the error persists) is to delete the cache: delete the .next folder and restart the server

The full example code from Next documentation is here

Allnight answered 24/2, 2021 at 8:20 Comment(0)
S
4

Finally the one and only solution that worked was to rename .babelrc.json to babel.config.json. If someone still getting this error here i leave reference how to fix that solution

Socinian answered 10/11, 2020 at 7:25 Comment(0)
E
2

What worked for me was:

  • Create a .babelrc (on the root).

  • inside the .babelrc:

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

Expendable answered 3/7, 2022 at 19:38 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Phillip
D
1

I too had this issue and clearing my cache/restarting my dev server seems to have fix the issue so far.

Dingbat answered 14/10, 2020 at 1:49 Comment(0)
F
1

I found the solution was to delete the .next folder, then npm run dev again the error disappeared. This is strange, sometimes you don't know where the error comes from but just try clearing the cache and restarting it might work!

Fumy answered 15/3 at 1:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.