0

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!

1 Answer 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)

Sign up to request clarification or add additional context in comments.

3 Comments

You're a hero! Thank you so much!
halo, i try to implement this code, but the state is still 0, whats wrong with that? @Ironessence
@FarhatDje Its because of closure, empty dependency array means useEffect will only be called on the first render and window.scrollY inside handleScroll will always be 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.