You can use (e: React.UIEvent<HTMLElement>)
. Described under the UIEvent from SyntheticEvents.
That said, I would advise against using useRef
within a useEffect
. It's tricky to determine whether useEffect
was re-called and scroller.current
wasn't null (even console.log
can be misleading about it).
However I would suggest to instead use the inbuilt onScroll
prop on the component you are attaching the ref
to, and give it a callback to handle the scroll. That way you don't need to attach it manually in the useEffect hook where you are forgetting to remove it on unmount(memory leak problems).
interface IProps {
children: React.ReactNode;
getScrollTop: (scrollTop: number) => whatever;
// Your other Props
}
const ScrollComponent: React.FC<IProps> = ({
children,
getScrollTop,
// Your other props
}): JSX.Element => {
const handleScroll = (e: React.UIEvent<HTMLElement>): void => {
e.stopPropagation() // Handy if you want to prevent event bubbling to scrollable parent
console.log({
event: e,
target: e.target, // Note 1* scrollTop is undefined on e.target
currentTarget: e.currentTarget,
scrollTop: e.currentTarget.scrollTop,
});
const { scrollTop } = e.currentTarget;
getScrollTop(scrollTop);
};
return (
<div
// I am assuming you were referencing your scroller as follows.
// ref={scroller}
onScroll={handleScroll} // Use the onScroll prop instead.
>
{children}
</div>
);
};
Note *1:
scrollTop wont be available on e.target.scrollTop
, much as you can see in in the console.log
, but on e.currentTarget.scrollTop
, since currentTarget calls the element on which the event handler is attached to.