简体   繁体   中英

`className` did not match. Server:

I am using NextJS getServerSideProps to fetch data and the page is rendering correctly with the data. So this works fine except when rendering a dynamic classname property on a html element I am getting the following error:

Prop `className` did not match. Server: "" Client: "dark"

when rendering the following component:

function Header(props: { darkMode: boolean }) {
  const [darkMode, setDarkMode] = useState(props.darkMode);
  
  return (
      <div className={(darkMode ? "dark" : "")}></div>   
  );
 }
 export default Header;

When debugging I can see that darkMode is true but the div element is still rendered without the className, assuming it's due to the error descriped above.

I am actually using MaterialUI although this element is not an materialUI element.

I have specified.bablerc like this:

{
  "presets": ["next/babel"],
  "plugins": [["styled-components", { "ssr": true }]]
}

Any idea why I am getting this error?

It seem like the issue is the same as the one mentioned here . If that's the case, I have posted the answer there

The className mismatch is related to how React syncs up the DOM node after a page is server-side rendered. Since React will only patch/sync the text context for the node and className is an attribute. A warning is triggered.

Reference

https://github.com/facebook/react/issues/11128#issuecomment-334882514

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM