Wrong styles applied during SSR hydration
See original GitHub issueStyled components is applying wrong styles during SSR hydration. The problem is that styles in production builds are swapped across components. For instance, the class sc-16rshtk
is applied to a ToolbarContainer but contains the styles of a FooterLink. I’m using gatsby with gatsby-theme-material-ui and gatsby-plugin-styled-components.
This didn’t happen for client side rendering, only for SSR. Since it only affected components styled with styled-components, I tried to collect more information by assigning a displayName to each component, but it did nothing, classnames remained the same.
Then I found #261 and saw this comment. It says that styled-components should not be re-exported to make displayName work.
import styled from '../lib/styled-components'; // Does not work :(
import styled from 'styled-components'; // Works
After applying that change, I made a new production build and then discovered that SSR hydration was now working correctly. I suspect that babel-plugin-styled-components does not work if the package is re-exported.
This issue was very hard to debug.
If you were re-exporting the module to add theme type definitions, please use module augmentation instead.
// src/types/styled-components.ts
import type { Theme } from '@material-ui/core';
declare module 'styled-components' {
export interface DefaultTheme extends Theme {
}
}
Issue Analytics
- State:
- Created 2 years ago
- Comments:8 (1 by maintainers)
You probably should use
topLevelImportsPath
to importstyled()
from different location. Based on the tests this is supported, see https://github.com/styled-components/babel-plugin-styled-components/blob/main/test/fixtures/add-identifier-with-top-level-import-paths-and-named-import/.babelrc and https://github.com/styled-components/babel-plugin-styled-components/blob/main/test/fixtures/add-identifier-with-top-level-import-paths/.babelrcShould be confirmed by some of the maintainers.
Now just confusion. Although at first I didn’t know about
topLevelImportsPath
and I thought it was a bug.Also I would like to draw attention to how painful it was to find out that re-exporting the package was breaking SSR. Perhaps the debugging experience could be improved somehow or the documentation for the plugin could include a reference to
topLevelImportsPath
.I replicated the original problem in my project, used @mnajdova
topLevelImportsPath
to solve it and it worked.