2

Currently, I have this custom hook to detect whether the user has scroll down/up the page entire page, but how can I implement it to detect scroll down and up inside a div element??

By using a ref? Any suggestion?


export const useScrollDirection = () => {
  const [scrollDirection, setScrollDirection] = useState(null);
  const [prevOffset, setPrevOffset] = useState(0);

  console.log("prevOffset", prevOffset);
  const toggleScrollDirection = () => {
    let scrollY = window.scrollY;
    console.log("scrollY", scrollY);
    if (scrollY === 0) {
      setScrollDirection(null);
    }
    if (scrollY > prevOffset) {
      setScrollDirection("down");
    } else if (scrollY < prevOffset) {
      setScrollDirection("up");
    }
    setPrevOffset(scrollY);
  };
  useEffect(() => {
    window.addEventListener("scroll", toggleScrollDirection);
    return () => {
      window.removeEventListener("scroll", toggleScrollDirection);
    };
  });
  return scrollDirection;
};

Pep
  • 647
  • 6
  • 20
  • I think this article might help https://stackoverflow.com/questions/50412259/detecting-scrolling-direction-on-the-page-updating-prev-value – Hardik3296 Dec 30 '20 at 05:43

1 Answers1

0

First, create a variable inside componentDidMount() and initialize with the current scroll position. Then attach the handleScroll() to a target element. I am using this hope this will help you too.

componentDidMount() {
    this.prev = window.scrollY;
}
handleScroll = (e) => {
    //console.log("scrolling!", e.target.scrollTop);

    const window = e.target;

    if (this.prev > window.scrollTop) {
      console.log("scrolling up");
    } else if (this.prev < window.scrollTop) {
      console.log("scrolling down");
    }
    this.prev = window.scrollTop;
};

Then attach handleScroll() to the target element.

<div onScroll={this.handleScroll}>
</div>