I am currently trying to create a piece of code that will mode a div when the user scrolls past a certain place. to do this i used window.addEventListener('scroll', () => checkSection(scrollSection, setScrollSection))
where i pass both of the variables returned from React.useState(0)
, then from within the event listener i check to see if the window.scrollY
property is more than the value in the scrollSection
state and if so translate it with js. but no matter what i do the function provided to update the state isnt updating the state, its not slow its just not updating at all. I was wondering if this is because i passed it into an event listener?
Event Listener and useState Initialization
function SideNav(props: any) {
const [scrollSection, setScrollSection] = React.useState(0);
React.useEffect(() => {
window.addEventListener('scroll', () => checkSection(scrollSection, setScrollSection));
return () => {
window.removeEventListener('scroll', () => checkSection(scrollSection, setScrollSection));
};
}, []);
Function passed to event listener
function checkSection(scrollSection: number, setScrollSection: Function){
let scrollSections = [0, 1538, 2583, 2089, 3089]
const scrollY = window.scrollY;
setScrollSection(1);
console.log("scroll Y: "+scrollY);
console.log("section: "+scrollSection)
}