Skip to content Skip to sidebar Skip to footer

Failing To Use Document Object Inside Of React Component. "document Is Not Defined" Error

I've got some browser sniffing code that I'm using inside of a react component I'm getting this error on build, though, 'document is not defined' It also fails when I try it like

Solution 1:

When you are using Next.js, you should be aware that some of your code will be run in the server-side where window, document and other browser specific APIs will be not available.

Since useEffect hook only runs in the client-side, you can use it together with useState to achieve your goal:

importReact, { useState, useEffect } from"react";

constSomeComponent = ({ props }) => {
  const [isIE, setIsIE] = useState(false);
  useEffect(() => {
    setIsIE(document.documentMode);
  }, []);
  if (!isIE) returnnull;
  return<div>Some browser sniffing code here.</div>;
};

Solution 2:

Next.js is a SSR framework, your code will run both on server-side and client side. Window would be not defined when running on server-side. If you want to get property from window, you could try these way.

  1. Get the window when you need

    if (typeofwindow !== 'undefined') {
       console.log(window.document)
    }
    
  1. In some specific situation, you need to run your component only on client side. In that case, you could using dynamic.

    components/ClientSideComponent

    constClientSideComponent = props => {
        // You could get window directly in this component console.log(window.document)
        return (
          <div>
             run your code only on client side
          </div>
        )
    }
    

    pages/index

    importdynamic from 'next/dynamic';
    const ClientSideComponent = dynamic(() => import('../components/ClientSideComponent'), {
        ssr: false,
    });
    
    const HomePage = props => {
        return <ClientSideComponent />
    }
    

Post a Comment for "Failing To Use Document Object Inside Of React Component. "document Is Not Defined" Error"