Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expected server HTML to contain a matching <tag> in <tag>

We are using nextjs and getting this error at page refresh (or first load)

My error is:

react-dom.development.js:88 Warning: Expected server HTML to contain a matching <tag> in <tag>.

The code of our functional component looks like this:

export default MyComponent () {

  if(! props.something){  // ← this is causing the problem.
    return null;
  }

  return (
    <>
     HTML here ...
    </>
  )
}

From my understanding, SSR is different from client side rendering and this is why react is complaining.

The app is working fine but this error is showing in the console and we don't want to have many errors being thrown there as this may prevent us from seeing the real errors when they happens.


Solution:

The solution is to use dynamic imports and and wrap the component call into:

const MyDynamicComponent = dynamic(() => import('./myComponent'), {ssr: false});

//use it:
<MyDynamicComponent />

//OR :

const MyDynamicComponent = dynamic(() => import('./myComponent'))

//use it:
{typeof window !== 'undefined' && (
  <MyDynamicComponent />
)}
like image 811
redochka Avatar asked Jun 07 '20 08:06

redochka


3 Answers

May be importing your component dynamically should solve this. Below is the link you can refer; https://nextjs.org/docs/advanced-features/dynamic-import

like image 169
Zeeshan Avatar answered Nov 14 '22 23:11

Zeeshan


I've been looking for solution of a similar problem, but I was using react-window lib and the problem appeared to be in it. I passed different height to it, depends on whether it's loading on server or client, so it gave me back different elements.

My solution was to pass the same height at the beginning, but to change it to window.innerHeight on useEffect ( = on client load).

like image 39
Jorah-M Avatar answered Nov 14 '22 23:11

Jorah-M


When this happened to me on a Next project, I had not nested my html table elements properly. Specifically, didn't wrap my <tr> in a <tbody>

like image 34
user3236637 Avatar answered Nov 14 '22 22:11

user3236637