Class name mismatch when using material-ui components in styled-components
See original GitHub issueUsing styled
material-ui components results in a class name mismatch when rendered on the client.
- This is not a v0.x issue.
- I have searched the issues of this repository and believe that this is not a duplicate.
Expected Behavior
During server-side rendering, the generated class names should be the same as the generated class names on the client even when using styled
material-ui components.
Current Behavior
When using a material-ui component wrapped in styled
HOC, different rules are passed to the class name generator on server than on client resulting in class name mismatch.
Steps to Reproduce
- Use server-side rendering for material-ui (server-side rendering for
styled-components
doesn’t affect the issue) - Add
styled
components to your app. At this point, it generates the class names correctly. - Add material-ui components wrapped in
styled
HOC to your app, e.g.
const StyledCard = styled(Card)`
max-width: 382px;
`;
render() {
<StyledCard>
...
</StyledCard>
}
At this point there are more class names generated by the generator on client side and they are in the wrong order.
E.g. client:
MuiCard-root-1
MuiPaper-root-2
MuiPaper-rounded-3
MuiPaper-elevation0-4
MuiPaper-elevation1-5
MuiPaper-elevation2-6
MuiPaper-elevation3-7
MuiPaper-elevation4-8
...
MuiTouchRipple-childLeaving-149
MuiTouchRipple-childPulsate-150
server:
MuiCardContent-root-1
MuiTypography-root-2
MuiTypography-display4-3
MuiTypography-display3-4
MuiTypography-display2-5
MuiTypography-display1-6
MuiTypography-headline-7
MuiTypography-title-8
...
MuiPaper-elevation23-142
MuiPaper-elevation24-143
This causes the warning when rendering on client:
Warning: Prop
className
did not match. Server: “MuiTypography-root-2 MuiTypography-body2-10” Client: “MuiTypography-root-30 MuiTypography-body2-38”
This project can be used to reproduce the issue: https://github.com/geiszla/react-website-starter/tree/styled-components
Build with yarn dev
, start with yarn start
and navigate to localhost:8080
to view app.
SSR is in server/express.jsx
, client is in src/index.jsx
, wrapped material-ui component is in src/components/Login.jsx
.
Edit: The app will look broken, as I removed some styles for testing. The indicator of the problem should be the warning in the console.
Context
Your Environment
Tech | Version |
---|---|
Material-UI | v3.3.0 |
React | v16.5.2 |
Browser | Chromium 71.0.3575.0 (Developer Build) (64-bit) |
Styled Components | v4.0.2 |
Issue Analytics
- State:
- Created 5 years ago
- Comments:10 (6 by maintainers)
Top GitHub Comments
I think it was a problem in the tree traversing, the new v3/v4 doesn’t do it. It should not cause any problem with Material UI, just upgrade 🙂.
@geiszla Thank you for the reproduction repository, I will look into to. Also, keep in mind that you can use JSS with the styled-components API with very few lines of code: