Categories
React Answers

How to get the scroll position with React?

Spread the love

Sometimes, we want to get the scroll position with React.

In this article, we’ll look at how to get the scroll position with React.

How to get the scroll position with React?

To get the scroll position with React, we create our own hook.

For instance, we write

import { useEffect, useState } from "react";

export const useWindowScrollPositions = () => {
  const [scrollPosition, setPosition] = useState({ scrollX: 0, scrollY: 0 });

  useEffect(() => {
    const updatePosition = () => {
      setPosition({ scrollX: window.scrollX, scrollY: window.scrollY });
    };

    window.addEventListener("scroll", updatePosition);
    updatePosition();

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

  return scrollPosition;
};

to listen to the window scroll event with addEventListener.

We set updatePosition as the event listener.

In it, we get the x coordinate of the scroll position with window.scrollX.

And we get the x coordinate of the scroll position with window.scrollY .

We call setPositiion with an object with the values to update scrollPosition.

We remove the event listener with removeEventListener when the component unmounts.

Then we use it by writing

import { useWindowScrollPositions } from "path/to/useWindowScrollPositions";

export const MyComponent = () => {
  const { scrollX, scrollY } = useWindowScrollPositions();

  return (
    <div>
      Scroll position is ({scrollX}, {scrollY})
    </div>
  );
};

We call useWindowScrollPositions to return an object with the scroll coordinates.

Conclusion

To get the scroll position with React, we create our own hook.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *