Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React 16: Warning: Expected server HTML to contain a matching <div> in <div> due to State

I'm getting the following error using SSR

Warning: Expected server HTML to contain a matching <div> in <div>.

The issue is on the client when checking the browser width on component mount, and then setting the state of a component to render a mobile version of it instead.

But the server is defaulting the desktop version of the container as it is not aware of the browser width.

How do I deal with such a case? Can I somehow detect the browser width on the server and render the mobile container before sending to the client?

EDIT: For now I've decided to render the container when the component mounts. This way, both server and client side render nothing initially preventing this error.

I'm still open to a better solution

like image 314
Ivan M Avatar asked Oct 21 '17 17:10

Ivan M


2 Answers

This will solve the issue.

// Fix: Expected server HTML to contain a matching <a> in
const renderMethod = module.hot ? ReactDOM.render : ReactDOM.hydrate;
renderMethod(
  <BrowserRouter>
    <RoutersController data={data} routes={routes} />
  </BrowserRouter>,
  document.getElementById('root')
);
like image 66
小弟调调 Avatar answered Oct 20 '22 23:10

小弟调调


Gatsby

A recent feature flag of gatsby (introduced in v2.28, December 2020) ables to server-side render pages in dev environment.

This flag is set to true by default. In this case, you might see this error message in the console

Warning: Expected server HTML to contain a matching <div> in <div>.

You can disable this flag in gatsby.config.js file :

module.exports = {
  flags: {
    DEV_SSR: false,
  }
}

doc : https://www.gatsbyjs.com/docs/reference/release-notes/v2.28/#feature-flags-in-gatsby-configjs

like image 21
aquinq Avatar answered Oct 20 '22 23:10

aquinq