Categories
React Answers

How to Update the Style of a Component on Scroll in React?

Spread the love

Sometimes, we want to update the style of a component on scroll with React.

In this article, we’ll look at how to update the style of a component on scroll with React.

Update the Style of a Component on Scroll in React

We can add a scroll event listener into the useEffect hook callback to listen for the scroll event.

For instance, we can write:

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

export default function App() {
  const [offset, setOffset] = useState(0);

  useEffect(() => {
    window.onscroll = () => {
      setOffset(window.pageYOffset);
    };
  }, []);

  console.log(offset);

  return (
    <div>
      {Array(100)
        .fill()
        .map((_, i) => (
          <p>{i}</p>
        ))}
    </div>
  );
}

We have the offset state which we create with the useState hook.

Then we call the useEffect hook with a callback that sets the window.onscroll property to a function that calls setOffset to set the offset to the scroll position.

window.pageYOffset has the vertical scroll position of the browser window.

We then log the offset with console log.

And we render some content that requires scrolling to view in the return statement.

Now when we scroll up or down, we see offset logged from the console log.

Conclusion

We can add a scroll event listener into the useEffect hook callback to listen for the scroll event.

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 *