Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning: Prop `className` did not match in Next.JS site with Styled Components

I've searched Stack Overflow for similar questions but the answers either refer to old versions or aren't relevant to my situation.

I get the above error for the first component on the page which uses Styled Components. If I remove that component I get the error for the next one and so on, so I assume there's a problem with the hydration process and it's happening for every className.

I have a _document.tsx file which extends the Document class and has the following getInitialProps function

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

My hunch is that it is something to do with this code because before I upgraded to Typescript (and had to change my _app.tsx file) I didn't get this error, but I have no idea how to fix it.

Any help would really be appreciated.

like image 886
jonhobbs Avatar asked Mar 01 '23 20:03

jonhobbs


1 Answers

Try installing babel-plugin-styled-components, then add a .babelrc file to the root of the project with the following configuration. This ensures that no mismatches in classes generation occur during rehydration.

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

From the babel-plugin-styled-components's documentation:

By adding a unique identifier to every styled component, this plugin avoids checksum mismatches due to different class generation on the client and on the server. If you do not use this plugin and try to server-side render styled-components React will complain with an HTML attribute mismatch warning during rehydration.

like image 181
juliomalves Avatar answered Mar 05 '23 16:03

juliomalves