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?
>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);
}
}
});