Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do passive:false event listeners in React?

Tags:

reactjs

I need to do event.preventDefault() in an onWheel handler, because of a niche UI requirement where mousewheel will control a 'zoom' effect in a certain element.

But React sets passive: true on wheel events, so event.preventDefault() doesn't work.

Is there some escape hatch that lets you attach events manually in a safe way?

The only way I know is to use a ref and call ref.current.addEventListener within a useEffect. And I've tried that and it seems to work, but I think it goes against official advice, because (if I understand correctly) React won't know to re-run the effect if ref.current changes. And that would be a serious bug if it happens in the wild. Is there a safer way to do it?

like image 681
callum Avatar asked Jan 23 '26 12:01

callum


1 Answers

You are doing it right. If React does not provide a way for you to do it, then use the "escape hatch" they provide to get around that. Infact, scrolling is listed as one of the valid use cases for refs here https://react.dev/learn/manipulating-the-dom-with-refs

The ref element should not change as it is being managed by React. And if it does, it will trigger a re-render where you can catch any changes.

like image 194
pjaoko Avatar answered Jan 26 '26 20:01

pjaoko



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!