Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do React-horizontal scroll using mouse wheel

I have used tailwind-CSS on react js I want to scroll horizontally using mouse wheel when user hover over the card section so for pc users can scroll horizontally by using mouse wheel instead of both shift and mouse wheel. Live Anywhere

        <div className="flex space-x-3 overflow-y-scroll scrollbar-hide p-3 -ml-3">
          {cardsDate?.map(({ img, title }) => (
            <MediumCard key={img} img={img} title={title} /> 
          ))}
        </div>
    </section>

enter image description here

like image 888
Prashant Avatar asked Aug 24 '26 22:08

Prashant


1 Answers

You can use a custom scroll function as a ref to your div.

export function useHorizontalScroll() {
  const elRef = useRef();
  useEffect(() => {
    const el = elRef.current;
    if (el) {
      const onWheel = e => {
        if (e.deltaY == 0) return;
        e.preventDefault();
        el.scrollTo({
          left: el.scrollLeft + e.deltaY,
          behavior: "smooth"
        });
      };
      el.addEventListener("wheel", onWheel);
      return () => el.removeEventListener("wheel", onWheel);
    }
  }, []);
  return elRef;
}

The above function can be imported and used as follows:

    <div className="App" ref={scrollRef} style={{ overflow: "auto" }}>
      <div style={{ whiteSpace: "nowrap" }}>
        <Picture />
      </div>
    </div>

I created a codesandbox as an example.

like image 81
hd3adcode Avatar answered Aug 27 '26 12:08

hd3adcode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!