Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

cannot read 'offsetTop'

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
        }
    }
  });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading