Not able to scroll an element on click using useRef in React

Viewed 134

Code:

const scrollRef = useRef<HTMLDivElement | null>(null);
const onClickScroll = (scrollOffset: number) => {
  scrollRef!.current!.scrollLeft += scrollOffset;
};

Component:

<span className="flex">
 <ChevronLeftIcon className="h-5 w-5 text-white cursor-pointer" onClick={()=> onClickScroll(-20)}/>
 <ChevronRightIcon className="h-5 w-5 text-white cursor-pointer" onClick={() => onClickScroll(20)}/>
</span>

Scrollable component:

<div className="flex mt-5 w-[80rem] overflow-scroll overflow-y-clip scrollbar-hide" ref={scrollRef}>Somecode</div>

onClickScroll should trigger a scroll but doesn't happen.

1 Answers

You should call scrollTo() method, instead of trying to mutate the property. Try doing so:

const onClickScroll = (scrollOffset: number) => {
  scrollRef!.current!.scrollTo(scrollOffset, 0);
};
Related