Home > Enterprise >  cannot read 'offsetTop'
cannot read 'offsetTop'

Time:12-25

Hello my friends I'm using ReactJs with this project and I got this message in the console

Uncaught TypeError: Cannot read properties of undefined (reading 'offsetTop') at (About.js)

btw the cod is working but I wanna know how to remove/fix this message. The cod:-

  const [start, setStart] = useState(false);
  const secRef = useRef();

  window.addEventListener("scroll", function () {
    const secTop = secRef.current.offsetTop;
    if (window.scrollY >= secTop - 300) {
      setStart(true);
    }
  });

then i say if start is true add some class, and its working fine but whats wrong with the console message?

CodePudding user response:

This is something you need to perform after the component has mounted.

You can use React's useEffect hook for such "side effects":

useEffect(() => {
    window.addEventListener("scroll", function () {
        const secTop = secRef.current.offsetTop;
        if (window.scrollY >= secTop - 300) {
            setStart(true);
        }
    });
}, []);

I should note; you'll want to remove this event listener once the component is unmounted. You can do that inside a callback returned from your useEffect function. The following is a fairly common pattern:

useEffect(() => {
    // Define the on-scroll callback
    const callback = function () {
        const secTop = secRef.current.offsetTop;
        if (window.scrollY >= secTop - 300) {
            setStart(true);
        }
    };

    // Attach the callback after the component mounts
    window.addEventListener("scroll", callback);

    // Detach the callback before the component unmounts
    return () => window.removeEventListener("scroll", callback);
}, []);

Also, depending on your scenario, it may still be wise to follow Amila's advice and check that your reference exists (has been rendered).

CodePudding user response:

Your ref might not have initialized at that time. You can avoid the runtime error like below.

  window.addEventListener("scroll", function () {
    if(secRef.current) {
        const secTop = secRef.current.offsetTop;
        if (window.scrollY >= secTop - 300) {
          setStart(true);
        }
    }
  });
  • Related