styled components server and client mismatch when importing from a yarn workspaces common package

Viewed 343

I have a styled component called Button exported from packages/common (simple React app) that I would like to use in packages/landing-page (NextJs application).

When importing styled-components like this:

import styled, { css } from "styled-components";

const Button = styled.button`
// ...
`

the component works fine in my packages/landing-page app, but since it's server-side rendered, I get the classic server and client mismatch between styled components classes. I solved this problem for components internal to the NextJs project, importing always from styled-components/macro.

BUT this does not solve the mismatch for the imported styled component from packages/common.

How to solve the mismatch when the component comes from a different package?

1 Answers

You may be missing the following configuration in your .babelrc config file. This error is caused due rehydration issues. Without SSR config set to true you will have checksum errors in the communication between client and server. The config below should take care of it.

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

To understand more about rehydration I recommend this article: What the hell are hydration and rehydration

This is a short explanation from styled-components 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.

Related