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

11,824

Solution 1

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

Solution 2

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).

Share:
11,824
redochka
Author by

redochka

Updated on July 25, 2022

Comments

  • redochka
    redochka almost 2 years

    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 />
    )}
    
  • Olian04
    Olian04 almost 4 years
    Please avoid posting link only answers. This should either be a comment or you need to include the essential parts of those links in the question itself
  • Zeeshan
    Zeeshan almost 4 years
    Actually this was my first time answering the questions. Any ways I will remember this advice. Thanks.
  • redochka
    redochka almost 4 years
    @Zeeshan Thanks that was it... But not only, I had to wrap the component with {typeof window !== 'undefined' && (. I will accept your answer and update my question with the full solution.
  • Admin
    Admin over 2 years
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.