I'm trying to show/hide individual images from an array of images based on the scroll height positioning in React. The idea being that at each interval the previous image will hide and the next one will show.
So far I've managed to map out the array of images and track the scroll position in my function component using the useEffect hook, I've also given props to each image so they have a min and max height value, then I've written an if statement that will check whether the image falls within the criteria. My issue seems to be passing the values of the min/max height to the if statement then displaying the correct image, or maybe something altogether that I've missed.
const ScrollingHeader = (props) => {
const [imageVisible, setImageVisible] = useState(false);
useEffect(() => {
window.addEventListener("scroll", showImage);
return () =>
window.removeEventListener("scroll", showImage);
}, [])
const showImage = (props) => {
console.log(window.scrollY);
const minHeight = props.minHeight
const maxHeight = props.maxHeight
if (window.scrollY >= minHeight && window.scrollY <= maxHeight) {
setImageVisible(true)
} else {
setImageVisible(false)
}
}
return (
<TeamImagesWrapper>
<TeamSlideContainer>
{props.imagesArray.map((images, i) => (
<TeamImageSlide id={i} minHeight={i * 50 - 25} maxHeight={i * 50 + 25}>
{ imageVisible &&
<img src={images.image.sizes.src} index={i} />
}
</TeamImageSlide>
))}
</TeamSlideContainer>
<IntroPara>{props.introText}</IntroPara>
</TeamImagesWrapper>
)
}
export default ScrollingHeader