'How to move elements on scroll in React.js?

I am trying to create an E-commerce Store and I'm a beginner in React.JS. What I want is for 5 images to come together on top of eachother when the user scrolls. (so they should move TranslateX on scroll). Previously, on Vanilla Javascript I would have added a window.addEventListener('scroll') and then set a value like value = window.scrollY and then I would have selected the image I wanted to move and simply translateX or Y based on that value.

However, I'm not sure how to do this in React. Where can I set the window event listener? Is there a state needed, or useEffect?

I'm attaching an image so you can clearly see what I am trying to do:

enter image description here

What I have in react is the "Scroll" component which contains 2 divs

-1 div on the left 2/3 flex size containing all the images that should come together -1 div on the right 1/3 flex size containing the text and the button

inside the left div I have 5 images, and in CSS i've used position absolute to position them on top of eachother (they are all PNGs so they have transparent background).

How would I go about implementing this on my website?

HUGE thanks in advance!



Solution 1:[1]

You can save the scrollY in a useState, which you then use to transofrm your images. The window listeners can be loaded inside a useEffect. It (could) look like this:

const [scrollY, setScrollY] = useState(0);

  useEffect(() => {
    const handleScroll = () => {
      setScrollY(window.scrollY);
    };
    handleScroll();

    window.addEventListener("scroll", handleScroll);
    return () => {
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

(You may have to add some ESLint rules if you use it)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nudelsuppe_42_