Next.js: Warning: Prop `className` did not match.

Created on 3 Jan 2020  路  2Comments  路  Source: vercel/next.js

Bug report

Describe the bug

I have read #7322 #7423, which is similar to my questions.
However, I don't use any Styled components and these solutions above can not help me.

To Reproduce

  1. Go to nextjs-classname-not-match
  2. Clone the repository and run
  3. See the Warning: Prop className did not match
  4. Also, yon can see the token is on the screen, but className can't be bind on the DOM.

Expected behavior

The className of 'token' should be bind on the DOM correctly.

Screenshots

鎴湒 2020-01-03 涓婂崍11 23 42
鎴湒 2020-01-03 涓婂崍11 24 51

System information

  • OS: mac
  • Browser: chrome 79
  • Version of Next.js: latest (9.1.6)

Most helpful comment

This makes a lot of sense, as you are using a browser functionality and you are expecting it to work on the server as well.

export default () => {
  const token = process.browser ? localStorage.getItem('token') : ''
  const className = token ? 'token' : ''
  console.log('className:', className);

  return (
    <div className={className}>
      {token}
    </div>
  )
}

To fix your problem, I would wrap that code in an useEffect call and update it when mounted.

This is not a nextjs specific problem, but how react SSR hydration works.
For further issues, please ask here https://spectrum.chat/zeit.

Close this bug request.

All 2 comments

This makes a lot of sense, as you are using a browser functionality and you are expecting it to work on the server as well.

export default () => {
  const token = process.browser ? localStorage.getItem('token') : ''
  const className = token ? 'token' : ''
  console.log('className:', className);

  return (
    <div className={className}>
      {token}
    </div>
  )
}

To fix your problem, I would wrap that code in an useEffect call and update it when mounted.

This is not a nextjs specific problem, but how react SSR hydration works.
For further issues, please ask here https://spectrum.chat/zeit.

Close this bug request.

This makes a lot of sense, as you are using a browser functionality and you are expecting it to work on the server as well.

export default () => {
  const token = process.browser ? localStorage.getItem('token') : ''
  const className = token ? 'token' : ''
  console.log('className:', className);

  return (
    <div className={className}>
      {token}
    </div>
  )
}

To fix your problem, I would wrap that code in an useEffect call and update it when mounted.

This is not a nextjs specific problem, but how react SSR hydration works.
For further issues, please ask here https://spectrum.chat/zeit.

Close this bug request.

Thanks, It is fixed by using useEffect.

Was this page helpful?
0 / 5 - 0 ratings