I have got Component with scroll bar inside it. I would like to know when the scroll bar reaches the top of the component.
Please if anybody can guide me...
I have got Component with scroll bar inside it. I would like to know when the scroll bar reaches the top of the component.
Please if anybody can guide me...
Created an example for you on codesandbox
Simplified example:
function Component() {
const ref = useRef(null);
useEffect(() => {
const element = ref.current;
const handleScroll = (e) => {
if (element.scrollTop === 0) {
console.log("do something");
// do whatever you want here
}
};
element.addEventListener("scroll", handleScroll);
return () => element.removeEventListener("scroll", handleScroll);
}, []);
return (
<div ref={ref}></div>
);
}
You can also make a hook out of it if you want to.
You can use the scroll event. No need for ref.
class MyComponent extends React.Component {
handleScroll=(evt)=> { // use this of object instance
if(!evt.currentTarget.scrollTop) {
}
}
render() {
return '<div onScroll={this.handleScroll}></div>';
}
}