5

I have created small nextjs page using wordpress REST API, Now react-hydration-error error show this page.I am using react html parser npm. How do I solve this error. could you please solve this error.

my code:

import Image from 'next/image'
import React ,{Component}from 'react'
import Link from 'next/link';
import { BiCalendar } from "react-icons/bi";
import ReactHtmlParser from 'react-html-parser'; 

export default class Blog extends Component{
    constructor(props){
        super(props);
        this.state={
        data: props.bloglist,
        isLoading: true,
        dataLoaded: false,
        };
       
    }
render(){
    if (!this.state.data) {
        return null;
      }
    console.log(this.state.data)
    return( 
        <>
        <div className="container blog-section">
            <div className='row'>
                <h2>Latest Posts</h2>
            </div>
            <div className='row'>
                {
                    this.state.data.map(((x,i) =>(
                        <div className='col-md-4 boxs text-center' key={i}>
                            
                            <div className='bg-info'>
                            <img src={x.images.large} className='img-fluid'/>
                            <h3>{x.title.rendered} </h3>
                            <p className='shopping'><span><BiCalendar/> {x.date}</span> </p>
                            {/* <p dangerouslySetInnerHTML={{__html: x.excerpt.rendered}}></p><span><BiShoppingBag/> {x.slug}</span> */}
                            <p class='expert'>{ReactHtmlParser(x.excerpt.rendered)}</p>
                            <Link href={"/blog"+"/"+x.slug+"/"+x.id } passHref={true}><p className='readmore'><span>Readmore </span></p></Link>
                        </div>
                        </div>
                    )))
                }
            </div>
        </div>
        </>
    )
}
}

My original issues: paragraph coming this format <p>If you have heard that there are ways to make money while shopping in the UAE and would lik</p> from API, So I converted to html.

siva
  • 69
  • 1
  • 1
  • 4
  • 1
    This is quite a common issue in Next.js and a lot of times it's caused by incorrect JSX wrapping patterns. [Check this question](https://stackoverflow.com/questions/72662294/can-i-pass-data-fetched-in-getstaticprops-to-a-component/72665172#72665172), maybe it can help you solve your problem. – ivanatias Jul 29 '22 at 21:09
  • 1
    Also, for these errors, the console will provide you with very useful hints about where is the actual problem, look out for warnings like Warning: Expected server HTML to contain a matching
    in
    .
    – ivanatias Jul 29 '22 at 21:16
  • Can you please provide the full warning/error you're getting? – juliomalves Jul 29 '22 at 22:44
  • You should check this (https://nextjs.org/docs/messages/react-hydration-error). – Adnan Mar 24 '23 at 07:03

8 Answers8

11

I had this error, in my case I had <p> tag nested inside another <p> tag,

I was using Typography (MUI v5) to render text, switching to <Box> from <Typography> fixed the error.

atazmin
  • 4,757
  • 1
  • 32
  • 23
4

We use components to build the React-based websites, These components are made using HTML tags. It is very important not to nest the same HTML elements.

For Example:

function Logo() {
  return (
    <Link href="/">
      <a>
        <Image
          src="/images/logo.svg"
          width={100}
          height={75}
        />
     </a>
   </Link>
  );
}

export default Logo;

Above is the Logo Component which has already the <a></a> tag inside it.

In this example, you will get the React Hydration Error if the <a> tag is used inside another <a> tag.

<a href="#">
   <Logo />
</a>

enter image description here


So do not include the same HTML tags, which are hidden inside the components to avoid react hydration error.

Dinesh Sunny
  • 4,663
  • 3
  • 30
  • 29
2

You can use this trick to check if the component has been mounted

  const [isMounted, setIsMounted] = useState(false);

  useEffect(() => {
    setIsMounted(true);
  }, []);

  if (!isMounted) {
    return null;
  }
onmyway133
  • 45,645
  • 31
  • 257
  • 263
1

My first code was this:

const isUserLoggedIn = is_user_logged_in()
// is_user_logged_in() checks for cookie of user token and returns boolean

Got the error about hydration Then changed code to this:

const [isUserLoggedIn, setIsUserLoggedIn] = useState(null)

useEffect(() => {
    setIsUserLoggedIn(is_user_logged_in())
}, [])

Renders was like this:

{isUserLoggedIn ? (
    <>
        {/* After login */}
        <Profile USER={USER}/>
    </>
) : (
    <>
        {/* Before login */}
        <SigninButtons/>
    </>
)}

And error solved

You can also check this https://nextjs.org/docs/messages/react-hydration-error

0

In my case I am using NextJS and I had a dropdown with react-select, the default value was changing after a small calculation, that does not like to nextjs, this is my previous code:

  <Select options={seasons}
          onChange={() => setSeason(e.value)}
          defaultValue={seasons.find((x) => x.value == season) ? seasons.find((x) => x.value == season) : seasons[0]}
  />

So, I changed that calculation to the useEffect and initialized the react-select dropdown only when that value was calculated,now this is my current code that works:

{defaultSeason && (<Select options={seasons}
        onChange={() => setSeason(e.value)}
        defaultValue={defaultSeason}
/>)}

So, basically check that the defaultValue or anything else does not change after the html is sent to the client part in NextJS.

Dayán Ruiz
  • 611
  • 1
  • 9
  • 22
0

Follow these: https://nextjs.org/docs/messages/react-hydration-error

Or try deleting <a> within <Link> maybe.

Turjoy Saha
  • 107
  • 1
  • 4
-1

I had the same issue with each of my first two NextJS applications but I found a good found resource that could be of help: https://javascript.plainenglish.io/how-to-solve-hydration-error-in-next-js-a50ec54bfc02

Solution 1: useEffect/componentDidMount

const [expand, setExpand] = React.useState(true);

// to avoid SSR error

useEffect(() => {
    setExpand(localStorage.getItem(EXPAND_STORAGE_KEY) === '1');
}, []);

Solution 2: react-no-ssr

npm i --save react-no-ssr

import React from 'react';
import NoSSR from 'react-no-ssr';
import Comments from './comments.jsx';
 
const MyPage = () => (
  <div>
    <h2>My Blog Post</h2>
    <hr />
    <NoSSR>
      <Comments />
    </NoSSR>
  </div>

Solution 3: Turn off SSR

Why Hydration Error is happening:

CSR is limited to running in the browser and SSR needs to be able to run in both browser and server which meets some problems and challenges that not happened in pure CSR apps. In terms of user experience, SSR will indeed bring a great improvement to our application.
-2
  1. Just try restarting the server. npm run dev. It worked for me. I was using react-hot-toaster.
  2. Also try to check if you have sth like this:

<p>
<div>
Hello
</div>
</p>

div cant be inside p tag