Search code examples
javascriptreactjsnext.jstailwind-css

Error: There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering


I am making a website using Next.js and the above error is shown every time.

Don't know what is wrong in my code.

const Login = () => {
  const [userMsg, setUserMsg] = useState("");
  const [email, setEmail] = useState("");
  const router=useRouter();

  const handleOnChangeEmail = (e) => {
    e.preventDefault();
    setUserMsg("");
    console.log("event", e);
    const email = e.target.value;
    setEmail(email);
  };
  const handleLoginWithEmail = (e) => {
    e.preventDefault();
    if (email) {
      if (IsEmail.validate(email)){
        router.push("/")
        
      }else{
        setUserMsg("Enter a valid email address")
      }
      
    } else {
      //show usermssg
      setUserMsg("Enter an email address");
    }
  };
  return (
    <div className="bg-[url('/static/bglg.jpg')] flex items-stretch flex-col h-screen w-full">
      <head>
        <title>NeoVest SignIn</title>
      </head>
      <header className="text-4xl px-10 py-2 font-black">
        <span className="text-indigo-700">NeoVest</span>
      </header>
      <div className="w-full max-w-xs m-auto bg-[#C9C9C9] rounded p-5 bg-opacity-50 border-gray-200">
        <header>
          <div className="text-indigo-700 font-black text-3xl py-2">
            <p>Sign In</p>
          </div>
        </header>
        <form className="py-5">
          <div>
            <label className="block mb-2 text-indigo-500" for="username">
              Email
            </label>
            <input
              className="w-full p-2 mb-6 text-indigo-700 border-b-2 border-indigo-500 outline-none focus:bg-gray-300"
              type="text"
              name="username"
              placeholder="Email Address"
              onChange={handleOnChangeEmail}
            />
            <div className="block mb-2 text-red-700">
              <p>{userMsg}</p>
            </div>
          </div>
          <div>
            <input
              className="w-full bg-indigo-700 hover:bg-pink-700 text-white font-bold py-2 px-4 mb-6 rounded"
              type="button"
              value="Submit"
              onClick={handleLoginWithEmail}
            />
          </div>
        </form>
      </div>
    </div>
  );
};

Another error shown is due to some suspense boundary causing root to switch to client side rendering :

Error: There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering.

I am also using Tailwind if that information is important.


Solution

  • If you would look at the console you would see a warning.

    Warning: validateDOMNesting(...): <head> cannot appear as a child of <div>
    

    So, to fix this you just have to move head out of the div and move it to a different higher component.