I am trying to figure out how to implement window.addEventListener in React. I'm developing a website with Gatsby and in "development" environment it works but whenever I start in production it gets an error. This is my code:
const checkHeader = () => {
// Detect scroll position
let viewportWidth = window.innerWidth || document.documentElement.clientWidth;
if (viewportWidth > 1100) {
let scrollPosition = Math.round(window.scrollY);
if (scrollPosition > 100){
document.querySelector('#nav').classList.add(`${headerStyles.sticky}`);
}
else {
document.querySelector('#nav').classList.remove(`${headerStyles.sticky}`);
}
} else {
}
};
// Run the checkHeader function every time you scroll
window.addEventListener('scroll', checkHeader);
I want to apply a class when Scroll. I've checked that I can't use "window." in React. How is the way to implement this code in React?
eventlistenerand set the class based on the state varaible in the rendeer.