My bet here is using Function components with new hooks to solve it, but instead of using useEffect
like in previous answers, I think the correct option would be useLayoutEffect
for an important reason:
The signature is identical to useEffect, but it fires synchronously after all DOM mutations.
This can be found in React documentation. If we use useEffect
instead and we reload the page already scrolled, scrolled will be false and our class will not be applied, causing an unwanted behavior.
An example:
import React, { useState, useLayoutEffect } from "react"
const Mycomponent = (props) => {
const [scrolled, setScrolled] = useState(false)
useLayoutEffect(() => {
const handleScroll = e => {
setScrolled(window.scrollY > 0)
}
window.addEventListener("scroll", handleScroll)
return () => {
window.removeEventListener("scroll", handleScroll)
}
}, [])
...
return (
<div className={scrolled ? "myComponent--scrolled" : ""}>
...
</div>
)
}
A possible solution to the problem could be https://codepen.io/dcalderon/pen/mdJzOYq
const Item = (props) => {
const [scrollY, setScrollY] = React.useState(0)
React.useLayoutEffect(() => {
const handleScroll = e => {
setScrollY(window.scrollY)
}
window.addEventListener("scroll", handleScroll)
return () => {
window.removeEventListener("scroll", handleScroll)
}
}, [])
return (
<div class="item" style={{'--scrollY': `${Math.min(0, scrollY/3 - 60)}px`}}>
Item
</div>
)
}