I'm using fixed positioning to try and create a simple parallax effect
export const Home = () => {
const paralaxref = React.useRef();
const backdropImgStyle = {
height: '200vh',
position: 'fixed',
top: paralaxref.current?.clientHeight? window.pageYOffset / paralaxref.current.clientHeight*-500 : 0,
left: 0,
zIndex: -100,
filter: 'grayscale(.7)',
}
however, it doesn't update as I scroll how would I do that?
---EDIT--- Final solution for anyone in the future:
export const Home = () => {
const paralaxref = React.useRef();
const [paralaxPosition, setParalaxPosition] = React.useState(0);
useEffect(() => {
window.onscroll = () => {
setParalaxPosition(paralaxref.current?.clientHeight? window.pageYOffset / paralaxref.current.clientHeight*-window.innerHeight : 0)
//(returns 0-1 for percent scrolled)*(multiplier for image height)
}
}, [])
const backdropImgStyle = {
height: '200vh',
width: '100vw',
position: 'fixed',
top: paralaxPosition,
left: 0,
right: 0,
zIndex: -100,
}
return(
<div ref={paralaxref} style={foregroundStyle}>
<img style={backdropImgStyle}
src={"https://i.imgur.com/image.png"}/>
use window.onScroll and then update your component styles inside it. This will work but use it inside useEffect and you can remove the listener when component will unmount.
useEffect(() => {
window.onscroll = () => {
// add logic
}
}, []);