How to Toggle Class based on Scroll Position with React?

Sometimes, we want to toggle class based on scroll position with React.

In this article, we’ll look at how to toggle class based on scroll position with React.

Toggle Class based on Scroll Position with React

To toggle class based on scroll position with React, we can listen to the scroll event on the scroll container element.

For instance, we write:

import React, { useEffect, useState } from "react";

export const useScrollHandler = () => {
  const [scroll, setScroll] = useState(1);

  useEffect(() => {
    const onScroll = () => {
      const scrollCheck = window.scrollY > 10;
      setScroll(scrollCheck);
    };

    document.addEventListener("scroll", onScroll);
    return () => {
      document.removeEventListener("scroll", onScroll);
    };
  }, [scroll, setScroll]);

  return scroll;
};

export default function App() {
  const scroll = useScrollHandler();

  return (
    <div style={{ color: scroll ? "red" : "green" }}>
      {Array(200)
        .fill()
        .map((_, i) => (
          <p key={i}>{i}</p>
        ))}
    </div>
  );
}

to define the useScrollHandler hook to watch the scroll event on the document.

We have the scroll state that’s set to true if we scroll more than 10 pixels down the page.

We call setScroll to set the state of scroll in onScroll.

Then we onScroll as the document‘s scroll evnt handler with document.addEventListener.

And we return a function that calls document.removeEventListener to remove the scroll event listener when we unmount the component.

Finally, we return the scroll state so it can be used in other components.

In App, we have some content that we can scroll through.

And we call the useScrollHandler hook to return the scroll state, which is true when we scroll more than 10 pixels down the page and false otherwise.

We set the style prop of to an object with the color property to set the color of the text depending of the value of scroll.

Now we should see green text when we’re at the top of the page and red text when we scroll down.

Conclusion

To toggle class based on scroll position with React, we can listen to the scroll event on the scroll container element.