skip to Main Content

I have div which has onWheel.

Browser treat onWheel as scroll by default.

However I want to stop mouse browser behaivor in under condition.

However, for now I bumped into Unable to preventDefault inside passive event listener invocation error. some article says I should use { passive: false } in addEventListener, but how can I do this in React?

handleWheel(e){
    if (e.ctrlKey){
        console.log("wheel is called, then want to stop scroll!!");
        e.stopPropagation(); //It doesn't stop default scroll behaivor.
        e.preventDefault();   //it shows the error Unable to preventDefault inside passive event listener invocation.
    }
}

    <div onWheel={handleWheel} >

2

Answers


  1. please try like below:

    document.getElementById("divScroll").addEventListener('wheel', function(e) {
      // your logic
    }, {passive:false});
    
    <div id="divScroll" >
    
    Login or Signup to reply.
  2. as the error message mentioned:

    Unable to preventDefault inside passive event listener invocation

    you have explicit to set the event listener to active by { passive: false }

    "use client";
    
    import { useEffect, useRef } from "react";
    
    const Page = () => {
      const ref = useRef<HTMLDivElement>(null);
    
      useEffect(() => {
        const element = ref.current;
        element?.addEventListener("wheel", handleWheel, { passive: false });
      }, []);
    
      const handleWheel = (event: any) => {
        if (event.ctrlKey) {
          event.preventDefault();
          event.stopPropagation();
        }
      };
    
      return (
        <div>
          <div ref={ref} className="h-96 w-96 bg-red-300"></div>
        </div>
      );
    };
    export default Page;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search