Sometimes, we want to add scroll event listeners in a React component.
In this article, we’ll look at how to add scroll event listeners in a React component.
How to add scroll event listeners in a React component?
To add scroll event listeners in a React component, we can set the onScroll
prop of an element to an event handler function.
For instance, we write:
import React from "react";
export default function App() {
const onScroll = (e) => console.log(e);
return (
<div onScroll={onScroll} style={{ height: 50, overflowY: "scroll" }}>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed lobortis,
elit at varius euismod, felis felis scelerisque lacus, at laoreet neque
nisi sit amet arcu. Nullam placerat porttitor justo, non pretium justo
fringilla aliquam. Vivamus vel odio imperdiet nisi faucibus hendrerit.
Nunc finibus nisi faucibus nulla ultrices, nec consequat tellus
condimentum. Cras et pulvinar augue. Aliquam laoreet dolor ultrices mi
laoreet, in laoreet enim venenatis. Sed faucibus ipsum nec quam iaculis,
</div>
);
}
We create the onScroll
function that logs the scroll event object.
Then we assign the onScroll
function as the value of the onScroll
prop of the div.
Now when we scroll up and down, we should see the scroll event object logged.
Conclusion
To add scroll event listeners in a React component, we can set the onScroll
prop of an element to an event handler function.