Skip to content

Commit

Permalink
Add additional fix in hydration error document (#40675)
Browse files Browse the repository at this point in the history
I had the same issue, so the fix that worked for me was pulled from this
thread https://stackoverflow.com/a/71870995

I have been experiencing the same problem lately with NextJS and i am
not sure if my observations are applicable to other libraries. I had
been wrapping my components with an improper tag that is, NextJS is not
comfortable having a p tag wrapping your divs, sections etc so it will
yell "Hydration failed because the initial UI does not match what was
rendered on the server". So I solved this problem by examining how my
elements were wrapping each other. With material UI you would need to be
cautious for example if you use a Typography component as a wrapper, the
default value of the component prop is "p" so you will experience the
error if you don't change the component value to something semantic. So
in my own opinion based on my personal experience the problem is caused
by improper arrangement of html elements and to solve the problem in the
context of NextJS one will have to reevaluate how they are arranging
their html element

<!--
Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change that you're making:
-->


## Documentation / Examples

- [x] Make sure the linting passes by running `pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)

Co-authored-by: JJ Kasper <jj@jjsweb.site>
  • Loading branch information
abdennor and ijjk committed Sep 23, 2022
1 parent bebf372 commit 1bbd264
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions errors/react-hydration-error.md
Expand Up @@ -37,6 +37,40 @@ function MyComponent() {
}
```

Another example:

Invalid HTML may cause hydration mismatch such as div inside p.

```jsx
export const IncorrectComponent = () => {
return (
<p>
<div>
This is not correct and should never be done because the p tag has been
abused
</div>
<Image src="/vercel.svg" alt="" width="30" height="30" />
</p>
)
}
```

How to fix it:

```jsx
export const CorrectComponent = () => {
return (
<div>
<div>
This is correct and should work because a div is really good for this
task.
</div>
<Image src="/vercel.svg" alt="" width="30" height="30" />
</div>
)
}
```

Common causes with css-in-js libraries:

- When using Styled Components / Emotion
Expand Down

0 comments on commit 1bbd264

Please sign in to comment.