0

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;

Pratap Alok Raj
  • 1,098
  • 10
  • 19
Amr
  • 646
  • 1
  • 6
  • 21
  • Why are you hard coding it for 100, just scroll to section2 when offsetY > 0; – Pawan Bishnoi Jun 06 '21 at 12:01
  • @PawanBishnoi it will result infinite loop, the useEffect hook is dependent on the offsetY. it get called every time the offsetY changes. – Amr Jun 06 '21 at 12:07

0 Answers0