Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

reactjs - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...