NaN-Simon
NaN-Simon

Reputation: 148

nextJS+new Date() Error: Text content does not match server-rendered HTML. Warning: Text content did not match

I need to get a date in a component. I have built it with React, NextJS and M-UI. I received this error:

Unhandled Runtime Error Error: Text content does not match server-rendered HTML.

Warning: Text content did not match. Server: "Mon Apr 24 2023 20:52:32 GMT+0300 (GMT+03:00)" Client: "Mon Apr 24 2023 20:52:33 GMT+0300 (GMT+03:00)"

const UserHeader = () => {

  const alpha = new Date().toString()

  return (
    <Container>
      {alpha}
    </Container>
  )
}

I tried to use a common <div> and

const [alpha, setAlpha] = useState()

like this but it didn't help me.

Upvotes: 5

Views: 5176

Answers (2)

mob
mob

Reputation: 76

As pointed out in the linked article (https://nextjs.org/docs/messages/react-hydration-error#possible-ways-to-fix-it), another option is to disable server side prerendering of the component by replacing the component import with the following wherever the UserHeader component is being imported.

import dynamic from 'next/dynamic'
const UserHeader = dynamic(() => import('../components/user-header'), { ssr: false })

Upvotes: 0

Will Calderwood
Will Calderwood

Reputation: 4636

If you know why, understand and really aren't bothered then you can suppress the warning by adding the suppressHydrationWarning flag in the containing element.

      <span suppressHydrationWarning>
        {alpha}
      </span>

The suppression only goes one element deep, it doesn't pass to the children's children, so you'll still receive warnings from further down the tree that may be useful.

Upvotes: 1

Related Questions