Sometimes, we want to update a React component when we’re scrolling.
In this article, we’ll look at how to update a React component when scrolling.
Add a Scroll Event Listener
We can add a scroll event listener into the useEffect
hook to let us watch for scrolling events.
For instance, we can write:
import React, { useEffect, useState } from "react";
export default function App() {
const [scrollTop, setScrollTop] = useState();
const [scrolling, setScrolling] = useState();
useEffect(() => {
const onScroll = (e) => {
setScrollTop(e.target.documentElement.scrollTop);
setScrolling(e.target.documentElement.scrollTop > scrollTop);
};
window.addEventListener("scroll", onScroll);
return () => window.removeEventListener("scroll", onScroll);
}, [scrollTop]);
useEffect(() => {
console.log(scrolling);
}, [scrolling]);
return (
<div>
{Array(50)
.fill("foo")
.map((a, i) => {
return <p key={i}>{a}</p>;
})}
</div>
);
}
We create the scrollTop
and scrolling
states with the useState
hook.
Next, we call the useEffect
hook with a callback that calls addEventListener
to listen for scroll events triggered on the browser screen.
The onScroll
function sets the scrollTop
and scrolling
state values.
We know we’re scrolling when e.target.documentElement.scrollTop > scrollTop
is true
.
We return a callback that calls removeEventListener
to remove the scroll event listener when we unmount the component.
And we log the latest value of scrolling
in the useEffect
callback.
Finally, we return some content we can scroll through in the JSX.
Now when we scroll, we should see the latest value of scrolling
logged.
Conclusion
If we want to update a React component when scrolling, we can watch for scroll events that are triggered with an event listener.
Then we can do what we want in the event listener when we’re scrolling in the event handler.