Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR TYPESCRIPT

useHorizontalScroll react

// custom Hook
export const useHorizontalScroll = (scrollWidth: number) => {
  const elRef = useRef();
  useEffect(() => {
    const el = elRef.current as HTMLElement;
    if (el) {
      const onWheel = (e) => {
        console.log(el);

        if (e.deltaY == 0) return;
        e.preventDefault();
        el.scrollTo({
          left: el.scrollLeft + scrollWidth * e.deltaY,
          behavior: 'smooth',
        });
      };
      el.addEventListener('wheel', onWheel);
      return () => el.removeEventListener('wheel', onWheel);
    }
  });
  return elRef;
};

//useage inside a component

const Assessments = () => {
  const scrollRef = useHorizontalScroll(scrollWidth);
  return (
    <div
      ref={scrollRef}
      >
       ......
  )

 
PREVIOUS NEXT
Tagged: #useHorizontalScroll #react
ADD COMMENT
Topic
Name
4+4 =