i currently have a navbar component and would like to change its background color on scroll. I am trying to detect the scroll height but it is not working. Every time i open the console, my console.log keeps returning 0 meaning that the scroll is not getting detected. I have looked at many question regarding this problem and tried applying their solutions but still it is not working.
Here is my code:
Navbar.js
function Navbar() {
const[navbar,setNavbar]=useState(false);
const changeBackground=()=>{
console.log(window.scrollY)
if(window.scrollY >= 80){
setNavbar(true)
} else{
setNavbar(false)
}
}
window.addEventListener('scroll',changeBackground,true);
return (
<>
<div className={navbar ? 'navbar_container active':'navbar_container'}>
</div>
)
}
export default Navbar;
Navbar.css
.navbar_container {
align-items: center;
background-color: transparent;
color: white;
display: flex;
flex-direction: row;
height: 94px;
justify-content: space-between;
margin: 0 auto;
width: 98%;
z-index: 100;
position: fixed;
width: 100vw;
}
.navbar_container.active {
align-items: center;
background-color: black;
color: white;
display: flex;
flex-direction: row;
height: 94px;
justify-content: space-between;
margin: 0 auto;
width: 98%;
z-index: 100;
position: fixed;
width: 100vw;
}
Home.js
function Home(){
return(
<Navbar/>
)}