Trigger scroll event when user scroll up or down react.js

906 Views Asked by At

I'm trying to simulate Tesla's web app landing page scroll behavior using React.js and react-scroll

Scroll Behavior

Assume we have 2 sections, the hero image is section 1, and within a small scroll from the user, an event is triggered it scrolls down to the next section (section 2)

My question is how could I trigger the scroll event to scroll to section 2 when the user is scrolling down while he is on section 1, similarly to the Tesla landing page.

I have achieved it using listener on offsetY and a condition if it is equivalent to 100px if (offsetY === 100), the window will be scrolled to section 2. but that only could be achieved in equivalence to 100. in other words, the window will be scrolled if and only if it meets 100px relative to the document.

any thoughts or recommendations would be useful.


function App() {
  const [offsetY, setOffSetY] = useState(0);

  const handleScroll = (e) => {
    setOffSetY(window.pageYOffset)
  };

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

  useEffect(() => { // fires when the user scroll up or down, i.e. when the offsetY changes
    if (offsetY === 100) { // scroll to section 2 when the offsety is equal to 100px
      scroller.scrollTo("section2", {
        delay: 100,
        duration: 200,
        smooth: true
      })
    }
  }, [offsetY]);

  return (
    <React.Fragment>
        <div id="section1" style={{height:"500px", width:"100%", color:"black"}}>
        </div>
        <div id="section2" style={{height:"500px", width:"100%", color:"red"}}>
        </div>
    </React.Fragment>
  );
}

export default App;

0

There are 0 best solutions below