I was trying to make an element position : “fixed” after it scrolls to the end of the screen and whenever it comes back to the first screen it should again get the position as “relative” , but state is changing to true (fixed) when it scrolls to the end of the screen but when it scroll back it is not changing to false (relative).
const [fixed, setFixed] = useState(() => {
return false;
});
const scrollHandler = () => {
if (window.scrollY > window.innerHeight) {
if (!fixed) {
setFixed(true);
}
} else {
if (fixed) {
setFixed(false);
}
}
};
useEffect(() => {
window.addEventListener("scroll", scrollHandler);
return () => {
window.removeEventListener("scroll", scrollHandler);
};
}, []);
return (
<>
<div
style={{ position: `${fixed ? "fixed" : "relative"}` }}
className={classes.navigationBelt}
></div>
</> );
Here is the code explaination
I have taken a state named as “fixed” and initial Value as “false”
const [fixed, setFixed] = useState(() => {
return false;
});
I have added an eventListener on the window for the scroll, when the component mounts into the dom.
useEffect(() => {
window.addEventListener("scroll", scrollHandler);
return () => {
window.removeEventListener("scroll", scrollHandler);
};
}, []);
For Handling the scroll event I have created a function named as “scrollHandler”
const scrollHandler = () => {
if (window.scrollY > window.innerHeight) {
if (!fixed) {
setFixed(true);
}
} else {
if (fixed) {
setFixed(false);
}
}
};
I am setting the “fixed” to “true” when the scroll is more than the height of the window and making an element to “fixed”. Note : I am only updating the state when “fixed” state is false, otherwise it will cause multiple re-render.
return (
<>
<div
style={{ position: `${fixed ? "fixed" : "relative"}` }}
className={classes.navigationBelt}
></div>
</> );
It is working fine, but when it scrolls back and “else” condition hit still the state (“fixed”) is showing be false even though it has changed and element has already got fixed. Because of that setFixed(false) does not work as the outer condition is still false.
else {
if (fixed) {
setFixed(false);
}
}
I wanted to know why is this happening?