Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Warning: Prop className did not match. #7322

Closed
th0th opened this issue May 13, 2019 · 273 comments
Closed

Warning: Prop className did not match. #7322

th0th opened this issue May 13, 2019 · 273 comments
Labels
good first issue Easy to fix issues, good for newcomers

Comments

@th0th
Copy link

th0th commented May 13, 2019

Examples bug report

Example name

with-styled-components

Describe the bug

Also posted here: #2538

Using css prop introduced with styled-components v4 causes Warning: Prop className did not match..

To Reproduce

Add any HTML element with css prop.

Expected behavior

Correctly styled rendering on the server side without any warnings.

Screenshots

57497472-7b657c00-72e0-11e9-84c5-e7e5fa0d351c

System information

  • OS: Windows
  • Chrome
  • Version of Next.js: 8.1.0

Additional context

Here is an example I created to demonstrate the issue: https://codesandbox.io/embed/jlwvwyy0ow

Open this and refresh once the building is done: https://jlwvwyy0ow.sse.codesandbox.io/

@kumarabhirup
Copy link

Happens to me everytime. +1

@Tomekmularczyk
Copy link
Contributor

The same happens with Next v.7. This error doesn't occur when the server starts, only after making changes in the code.

@elliotbonneville
Copy link

I'm seeing the same error. It doesn't appear to affect the live app, but it's very annoying to have it constantly appearing locally.

@cabralada
Copy link

I have a similar error, but with inline style.

Warning: Prop `style` did not match. Server: "height:50px;margin-left:4vw;cursor:pointer;width:auto;margin-top:0px" Client: "height:30px;margin-left:4vw;cursor:pointer;width:auto;margin-top:6px"

😢

@th0th
Copy link
Author

th0th commented May 24, 2019

I hope once enough people raise their voices here this issue will get attention 🙂

@SarKurd
Copy link
Contributor

SarKurd commented May 26, 2019

I face this issue in my simple navbar active className, is there a workaround until official fix?

@timneutkens
Copy link
Member

Use 👍 on the initial issue instead of "+1" and "same problem".

If you do feel like posting +1 provide a clear and concise reproduction that is clearly reproducible. Otherwise the comment is not actionable.

This goes for any open-source project you're commenting on.

Thanks 🙏

@c0b41
Copy link
Contributor

c0b41 commented May 31, 2019

Seems like they fixed latest release this bug styled-components/styled-components#2563

@th0th
Copy link
Author

th0th commented May 31, 2019

Nope, that's a totally different log message, it is the one with yellow background on the screenshot I posted, it disappeared after the update.

First one, warning about different classNames is still there.

@Timer Timer added good first issue Easy to fix issues, good for newcomers help wanted labels Jun 14, 2019
@Timer
Copy link
Member

Timer commented Jun 14, 2019

Tagging this as up for grabs to investigate by a motivated contributor.

@quantizor
Copy link
Contributor

Hey there, please update babel-plugin-styled-components to the latest version which should fix css prop mismatches: https://github.com/styled-components/babel-plugin-styled-components/releases/tag/v1.10.1

I've noticed an error message in development still, but no ill effects from it so can be safely ignored.

@ThisIsEsh
Copy link

Still same after fix posted above, and can't ignore it. Having some layout problems when this error occurs.

@ShayDavidson
Copy link

ShayDavidson commented Jul 3, 2019

So do I, when this occurs I'm getting layout errors and my component go into a weird state where they do not render based on new props.

It happens for me in an inline style.

@quantizor
Copy link
Contributor

Make sure your babel plugin version is up to date, lots of fixes in the last couple weeks. We also made changes to how we do dev styles in v5 that largely address this issue

@ShayDavidson
Copy link

ShayDavidson commented Jul 3, 2019

The Prop 'style' does not match is not solved with the babel plugin upgrade.

@quantizor
Copy link
Contributor

"style" is an inline style and nothing to do with styled-components, so that's a totally separate issue

@jass-trix
Copy link

what's the fix for this one? i always get this warning everytime i refresh.
i always do refresh everytime change something, bad old habit 😅
everytime i do refresh it shows warning and the styling all gone

@masives
Copy link
Contributor

masives commented Jul 8, 2019

It appears to be an issue that backend generates styled component but client doesn't get it/doesn't use it and instead of using server side rendered style client generates it by itself.

edit: I just downloaded the example and couldn't reproduce the issue while using the same code as in your codepen sandbox. Tested in chrome and firefox and it behaves the same (no error nor warning).

@quantizor
Copy link
Contributor

@jass-trix have you tried the s-c v5 beta? We made a lot of changes to eliminate this issue.

@jass-trix
Copy link

@probablyup how to use this version?

@JohnGrisham
Copy link

It appears to be an issue that backend generates styled component but client doesn't get it/doesn't use it and instead of using server side rendered style client generates it by itself.

edit: I just downloaded the example and couldn't reproduce the issue while using the same code as in your codepen sandbox. Tested in chrome and firefox and it behaves the same (no error nor warning).

I have this issue as well after upgrading to next 9.0.2 and styled components 4.3.2 but it does not occur every time. I have to go in and out of debug a few times to replicate at certain points. I have attempted the fixes suggested through similar issues such as styled-components/babel-plugin-styled-components#78. Seems to only effect development and I'm experiencing layout breaks in one section of the app. Still not sure if it is related to styled components or next but it does seem to have to do with SSR classnames being different on client/server I'm using the recommended babel plugin to fix this. babel-plugin-styled-components

@quantizor
Copy link
Contributor

quantizor commented Jul 23, 2019 via email

@JohnGrisham
Copy link

I was in the process of trying the beta but I appreciate your quick response 👍 @probablyup

@sadekujjaman
Copy link

sadekujjaman commented Oct 22, 2021

I have solved this issue following these steps.

  1. Create a file named .babelrc in the root directory and configure the .babelrc file.
  2. delete the .next build folder(It stores some caches).
  3. Restart the server.
  4. Hot reload the browser.

.babelrc configuration file

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

@kameikay
Copy link

I have solved this issue following these steps.

  1. Create a file named .babelrc in the root directory and configure the .babelrc file.
  2. delete the .next build folder(It stores some caches).
  3. Restart the server.
  4. Hot reload the browser.

.babelrc configuration file

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

That's the only way to solve my problem... It's unfortunate to see that 2 years later, this issue still opened... Thanks.

@FilipeCovas
Copy link

FilipeCovas commented Nov 4, 2021

I have solved this issue following these steps.

  1. Create a file named .babelrc in the root directory and configure the .babelrc file.
  2. delete the .next build folder(It stores some caches).
  3. Restart the server.
  4. Hot reload the browser.

.babelrc configuration file

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

That's the only way to solve my problem... It's unfortunate to see that 2 years later, this issue still opened... Thanks.

but this way you will slow compilations(NextJs 12), because when you create .babelrc next js will change rust swc to babel causing decreasing compilation speed
Compilation using Rust is 17x faster than Babel and enabled by default using Next.js 12
https://nextjs.org/blog/next-12#faster-builds-and-fast-refresh-with-rust-compiler

@op2rules
Copy link

op2rules commented Nov 5, 2021

Not working yet in 12.0.3 without the babel config

@ToledoNicola
Copy link

ToledoNicola commented Nov 6, 2021

same v12
react-dom.development.js?ac89:67 Warning: Prop `style` did not match. Server: "position:absolute;top:0;left:0;bottom:0;right:0;box-sizing:border-box;padding:0;border:none;margin:auto;display:block;width:0;height:0;min-width:100%;max-width:100%;min-height:100%;max-height:100%;object-fit:contain;filter:blur(20px);background-size:contain;background-image:url(\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Flogo-lettere-nero.96fb6bd8.png&w=8&q=70\");background-position:0% 0%" Client: "position:absolute;top:0;left:0;bottom:0;right:0;box-sizing:border-box;padding:0;border:none;margin:auto;display:block;width:0;height:0;min-width:100%;max-width:100%;min-height:100%;max-height:100%;object-fit:contain;filter:blur(20px);background-size:contain;background-image:url(\"/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Flogo-lettere-bianco.8ebf6dc1.png&w=8&q=70\");background-position:0% 0%" at img at span

@simonpeters
Copy link

Having the same issue with a fresh next 12 repo and styled components

@Amirhosein-hshm
Copy link

i have enable swc typescript compiler i dont want to add any babel config because its automatically disabled swc compiler.
how can i fixed that? without babelify it

@justyn-clark
Copy link

Same problem here. I want Rust, not Babel.

"next": "^12.0.1",
"styled-components": "^5.3.3",

Screen Shot 2021-11-11 at 7 18 48 PM

@lglufiego
Copy link

And still happens. It's so freaking annoying

@dbehmoaras
Copy link

dbehmoaras commented Nov 12, 2021

This is still very much an open issue and should not be closed. The proposed fixes only work temporarily and this issue has not been addressed in the latest released despite what the devs have indicated.

@hellobrunao
Copy link

Hey guys, just reporting that I am facing the same problem. I am not using styled-components, in my case the error happens on react-grid-system.
I have deleted the .next folder, closed tab, reopened, and the error stills.

react-dom.development.js?ac89:67 Warning: Prop styledid not match. Server: "box-sizing:border-box;min-height:1px;position:relative;padding-left:15px;padding-right:15px;width:33.333333333333336%;flex-basis:33.333333333333336%;flex-grow:0;flex-shrink:0;max-width:33.333333333333336%;margin-left:0%;right:auto;left:auto" Client: "box-sizing:border-box;min-height:1px;position:relative;padding-left:15px;padding-right:15px;width:8.333333333333334%;flex-basis:8.333333333333334%;flex-grow:0;flex-shrink:0;max-width:8.333333333333334%;margin-left:0%;right:auto;left:auto"
I hope to see a fix for that error from NextJS team and if I find some workaround I'll be happy to drop it here.

=]

@timneutkens
Copy link
Member

timneutkens commented Nov 15, 2021

@justyn-clark @Amirhosein-hshm @simonpeters
If you want to use SWC and are using styled-components see #30174 (comment)

I hope to see a fix for that error from NextJS team and if I find some workaround I'll be happy to drop it here.

Unfortunately so many other comments have drowned the reply that explains why the warning is shown by React.

To clarify again: this is not an issue with Next.js, it's an issue with the specific library that you're using when it is hydrated by React (which is a feature of React). In general it's one of these that causes the mismatch on className:

  • When using Styled Components / Emotion
  • When using other css-in-js libraries
    • Similar to Styled Components / Emotion css-in-js libraries generally need configuration specified in their respective examples in the examples directory
  • When using a React library (e.g. the above comment about react-grid-system) or in the application's React Components
    • What we often see is that something similar to the code below is written which then causes a hydration mismatch as the first render in the browser has to match exactly with what was rendered on the server. Josh Comeau wrote a decent article about hydration which might be useful for you: https://www.joshwcomeau.com/react/the-perils-of-rehydration/. I've included a small example of what code causes a mismatch below:
    •   function MyComponent() {
             // This condition depends on `window` so in the first render of the browser the `color` variable will be different
        	const color = typeof window !== 'undefined' ? 'red' : 'blue
            // As color is passed as a prop there is a mismatch between what was rendered server-side vs what was rendered in the first render
        	return <h1 className={`title ${color}`}>Hello World!</h1>
        }
        
        
        // In order to prevent the first render from being different you can use `useEffect` which is only executed in the browser and is executed during hydration:
        import {useEffect, useState} from 'react'
        function MyComponent() {
             // The default value is 'blue', it will be used during pre-rendering and the first render in the browser (hydration)
             const [color, setColor] = useState('blue')
             // During hydration `useEffect` is called. `window` is available in `useEffect`. In this case because we know we're in the browser checking for window is not needed. If you need to read something from window that is fine though.
             // By calling `setColor` in `useEffect` a render is triggered after hydrating, this causes the "browser specific" value to be available. In this case 'red'.
             useEffect(() => setColor('red'), [])
            // As color is a state passed as a prop there is no mismatch between what was rendered server-side vs what was rendered in the first render. After useEffect runs the color is set to 'red'
        	return <h1 className={`title ${color}`}>Hello World!</h1>
        }

Unfortunately there is no way to pin these comments and I don't want to lock this thread. We'll have a look at potentially intercepting this particular error coming from React and adding a Next.js docs link to it similar to what we do for errors coming from Next.js itself.

@hellobrunao
Copy link

Hey @timneutkens ... thank you so much for your quick reply, and sorry not digging a bit more into the older replies, my bad.

Now I see the issue regarding hydration, and you are right, I had a condition verifying if window was available.

@op2rules
Copy link

op2rules commented Nov 17, 2021

Awesome, thanks @timneutkens !

Working with 12.0.4 and

module.exports = {
    experimental: {
        // Enables the styled-components SWC transform
        styledComponents: true
    }
}

@timneutkens
Copy link
Member

I've had @ijjk work on an error link for this warning, hopefully that will reduce the confusion around why the warning happens and steps to take to fix it in your app 👍: #31519

@adielBm
Copy link

adielBm commented Nov 23, 2021

Thank you @timneutkens & @joshwcomeau (In his article 'The Perils of Rehydration'.), you helped me a lot. ❤
I had the same problem with material-ui & Next.js.
This is the component I created, I wrapped components that need to be rendering on the client side.

import React from "react";

const ClientOnly = ({ children, ...delegated }) => {

  const [hasMounted, setHasMounted] = React.useState(false);

  React.useEffect(() => {
    setHasMounted(true);
  }, []);

  if (!hasMounted) return null

  return (
    <React.Fragment {...delegated}>
      {children}
    </React.Fragment>
  );
}

export default ClientOnly
<ClientOnly>
     <SomeComponnet/>
</ClientOnly>

@GunterJameda
Copy link

Thank you @timneutkens & @joshwcomeau (In his article 'The Perils of Rehydration'.), you helped me a lot. ❤ I had the same problem with material-ui & Next.js. This is the component I created, I wrapped components that need to be rendering on the client side.

import React from "react";

const ClientOnly = ({ children, ...delegated }) => {

  const [hasMounted, setHasMounted] = React.useState(false);

  React.useEffect(() => {
    setHasMounted(true);
  }, []);

  if (!hasMounted) return null

  return (
    <React.Fragment {...delegated}>
      {children}
    </React.Fragment>
  );
}

export default ClientOnly
<ClientOnly>
     <SomeComponnet/>
</ClientOnly>

FWIW, I tried a lot of solutions layed out in this thread and this was the only one that worked. I'm using NextJS 12 with Material UI 5

@dbehmoaras
Copy link

Thank you @timneutkens & @joshwcomeau (In his article 'The Perils of Rehydration'.), you helped me a lot. ❤ I had the same problem with material-ui & Next.js. This is the component I created, I wrapped components that need to be rendering on the client side.

import React from "react";

const ClientOnly = ({ children, ...delegated }) => {

  const [hasMounted, setHasMounted] = React.useState(false);

  React.useEffect(() => {
    setHasMounted(true);
  }, []);

  if (!hasMounted) return null

  return (
    <React.Fragment {...delegated}>
      {children}
    </React.Fragment>
  );
}

export default ClientOnly
<ClientOnly>
     <SomeComponnet/>
</ClientOnly>

FWIW, I tried a lot of solutions layed out in this thread and this was the only one that worked. I'm using NextJS 12 with Material UI 5

This is a good solution when running in dev, but it's unfortunate to need to include when the issue doesn't present itself when the bundle is built.

@justice-sh
Copy link

justice-sh commented Dec 30, 2021

Hey guys, I saw this article on Medium and fixed this. Like, follow the steps, copy and paste the code and you're golden.

https://binyamin.medium.com/solving-the-styled-components-warning-in-next-js-with-babel-83080e45a0ff

@9no1ayu
Copy link

9no1ayu commented Jan 1, 2022

Hi guys, I've tried so many solutions in this thread these couple few days, still get this warning.
After some experiments, I confirmed that warnings are all came from:

  1. my custom styled framer-motion components
  2. component which style will change between dark / light mode.

So I changed the way to import those components by using next/dynamic (with No SSR) and finally fixed this :D!

example:

// /pages/index.js

import dynamic from 'next/dynamic'

const CircleButtonWithNoSSR = dynamic(() => import('../components/Buttons/CircleButton'), { ssr: false })

const HomePage = () => {
  return (
    <p>Home Page Title</p>
    <CircleButtonWithNoSSR color='gold' whileHover={{ scale: 1.2 }} />
  )
}

export default HomePage
// /components/buttons/CircleButton.js

import styled from 'styled-components'
import { motion } from 'framer-motion'

const CircleButton = styled(motion.button)`
  color: ${({ theme, color }) => color ? color : theme.color.primary};
`

export default CircleButton

Update: After a day, I kind of restructured my code like this 😄

// /components/NoSsr.js

import dynamic from 'next/dynamic'

const NoSsr = ({ children }) => <>{children}</>

export default dynamic(() => Promise.resolve(NoSsr), { ssr: false })
// /pages/index.js

import NoSsr from '../components/NoSsr'
import CircleButton from '../components/buttons/CircleButton'

const HomePage = () => {
  return (
    <>
      <p>Home Page Title</p>
      <NoSsr>
        <CircleButton color='gold' whileHover={{ scale: 1.2 }} />
      </NoSsr>
    </>
  )
}

@TamPhilip
Copy link

Hi guys, I've tried so many solutions in this thread these couple few days, still get this warning. After some experiments, I confirmed that warnings are all came from my custom styled framer-motion components.

So I changed the way to import those motion components by using next/dynamic (with No SSR) and finally fixed this :D!

example:

// /pages/index.js

import dynamic from 'next/dynamic'

const CircleButtonWithNoSSR = dynamic(() => import('../components/Buttons/CircleButton'), { ssr: false })

const HomePage = () => {
  return (
    <p>Home Page Title</p>
    <CircleButtonWithNoSSR color='gold' whileHover={{ scale: 1.2 }} />
  )
}

export default HomePage
// /components/Buttons/CircleButton.js

import styled from 'styled-components'
import { motion } from 'framer-motion'

const CircleButton = styled(motion.button)`
  color: ${({ color }) => color ? color : 'red'};
`

export default CircleButton

Thank you so much! This fix worked for '@mui/styles/styled' too!

ikendoit added a commit to ikendoit/many-windows that referenced this issue Jan 2, 2022
9no1ayu pushed a commit to 9no1ayu/9no1ayu that referenced this issue Jan 2, 2022
1. Prop XXX did not match. Server: "null 或 AAA" Client: "OOO" → vercel/next.js#7322 (comment)
2. Transient Props 問題 → react 不認得的 prop 前面加 $ (component 本身也要加)
3. Tag Button Active 時的動畫做好 + 顏色改固定不隨機了
4. _document 因應 SSR 整個改寫 (參考 nextjs/example/with-styled-components)
5. 調整 theme 物件 color 的結構 (分為 toneColor(固定不變)、coreColor(亮暗模式會變))
6. 取消在變換 Tag 時的 shallow routing (breadcrumb 配合調整如果沒有那頁面就顯示普通文字)
arabello added a commit to espanso/hub-frontend that referenced this issue Jan 6, 2022
@milad-afkhami
Copy link

Hi guys, I've tried so many solutions in this thread these couple few days, still get this warning. After some experiments, I confirmed that warnings are all came from:

  1. my custom styled framer-motion components
  2. component which style will change between dark / light mode.

So I changed the way to import those components by using next/dynamic (with No SSR) and finally fixed this :D!

example:

// /pages/index.js

import dynamic from 'next/dynamic'

const CircleButtonWithNoSSR = dynamic(() => import('../components/Buttons/CircleButton'), { ssr: false })

const HomePage = () => {
  return (
    <p>Home Page Title</p>
    <CircleButtonWithNoSSR color='gold' whileHover={{ scale: 1.2 }} />
  )
}

export default HomePage
// /components/buttons/CircleButton.js

import styled from 'styled-components'
import { motion } from 'framer-motion'

const CircleButton = styled(motion.button)`
  color: ${({ theme, color }) => color ? color : theme.color.primary};
`

export default CircleButton

Update: After a day, I kind of restructured my code like this 😄

// /components/NoSsr.js

import dynamic from 'next/dynamic'

const NoSsr = ({ children }) => <>{children}</>

export default dynamic(() => Promise.resolve(NoSsr), { ssr: false })
// /pages/index.js

import NoSsr from '../components/NoSsr'
import CircleButton from '../components/buttons/CircleButton'

const HomePage = () => {
  return (
    <>
      <p>Home Page Title</p>
      <NoSsr>
        <CircleButton color='gold' whileHover={{ scale: 1.2 }} />
      </NoSsr>
    </>
  )
}

actually next.js has an undocumented noSSR function in "next/dynamic",
does anyone knows how to use it? I couldn't find it in docs.

@craigcosmo
Copy link

error: Prop className did not match. Server: "sc-iNGGcK fYiZeZ" Client: "sc-bdvvtL kZtKWc"

	"dependencies": {
		"@types/styled-components": "^5.1.22",
		"@zeit/next-sass": "^1.0.1",
		"next": "^12.0.10",
		"node-sass": "^4.14.1",
		"query-string": "^7.0.1",
		"react": "17.0.2",
		"react-dom": "17.0.2",
		"recoil": "^0.4.1",
		"sass": "^1.42.1",
		"styled-components": "^5.3.3"
	},
	"devDependencies": {
		"@types/node": "16.11.6",
		"@types/react": "17.0.34",
		"eslint": "7.32.0",
		"eslint-config-next": "12.0.3",
		"typescript": "4.4.4"
	}
/** @type {import('next').NextConfig} */
module.exports = {
	reactStrictMode: true,
	styledComponents: true,
}

I updated the to next 12.0.10, still got the issue

@belkocik
Copy link

belkocik commented Feb 7, 2022

For all: check your React Components if you import them correctly.

@vercel vercel locked as resolved and limited conversation to collaborators Feb 7, 2022
ivanproskuryakov added a commit to communa/frontend that referenced this issue Apr 10, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
good first issue Easy to fix issues, good for newcomers
Projects
None yet
Development

No branches or pull requests