DEV Community

Nadeem Khan
Nadeem Khan

Posted on

Detect Scroll Direction ReactJS

In these blog. I am detecting scroll direction either person id scrolling down or up. To use these concept you can make some better thing like Navbar. Render a Navbar when we scroll untill that it gets disappear. So I am explaining here only about scroll direction If you want the example then please let me know.

import React, {useEffect, useState, useCallback} from 'react';
import { Fragment } from 'react/cjs/react.production.min';
import styles from "./App.module.css";

const App = () => {
  const [y,
    setY] = useState(document.scrollingElement.scrollHeight);
  const [scrollDirection,
    setScrollDirection] = useState("you have not scrolled yet");

  const handleNavigation = useCallback((e) => {

    if (y > window.scrollY) {
      setScrollDirection("Scrolling Up");
      console.log("scrolling up");
    } else if (y < window.scrollY) {
      setScrollDirection("Scrolling Down");
      console.log("scrolling down");
    }
    setY(window.scrollY)
  }, [y]);

  useEffect(() => {

    window.addEventListener("scroll", handleNavigation);

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


  return (
    <Fragment>
    <div className={styles.main_container}>

    </div>
      <div>{scrollDirection}</div>
    </Fragment>
  )
}

export default App
Enter fullscreen mode Exit fullscreen mode

OutPut Result

Result

Discussion (0)