I recently implemented the useRef hook in my scroll function, specifying HTMLDivElement
as the type. However, I encountered an issue where I received the error message "Property 'clientHeight, scrollHeight, scrollTop' does not exist on type 'HTMLDivElement | null'."
Upon hovering over useRef, I saw the following information:
(alias) useRef<HTMLDivElement>(initialValue: HTMLDivElement | null): RefObject<HTMLDivElement> (+2 overloads) import useRef
const scrollRef = useRef<HTMLDivElement>(null);
const getActivityFeedOnScroll = () => {
const {scrollTop, scrollHeight, clientHeight} = scrollRef?.current;
scrollTop + clientHeight === scrollHeight && fetchNextPage();
};
To address this issue, I modified the code to include null guards for clearer code readability:
+ const getActivityFeedOnScroll = () => {
+ if (!scrollRef.current) return;
+ const {scrollTop, scrollHeight, clientHeight} = scrollRef.current;
+ if (scrollTop + clientHeight === scrollHeight) fetchNextPage();
+ };