DEV Community

terrierscript
terrierscript

Posted on

8

Suspend pinch-zoom on React Hooks

I create hooks that suspend mobile device pinch zoom.
This behavior not recommended, but we need sometime.

const useDisablePinchZoomEffect = () => {
  useEffect(() => {
    const disablePinchZoom = (e) => {
      if (e.touches.length > 1) {
        e.preventDefault()
      }
    }
    document.addEventListener("touchmove", disablePinchZoom, { passive: false })
    return () => {
      document.removeEventListener("touchmove", disablePinchZoom)
    }
  }, [])
}

If you want suspend pinch zoom partial area, you can use this component.


const SuspendPinchZoom = ({ children }) => {
  const ref = useRef(null)
  // const ref = useRef<HTMLDivElement>(null)

  useLayoutEffect(() => {
    const target = ref.current
    if (!target) return
    const disablePinchZoom = (e) => {
      if (e.touches.length > 1) {
        e.preventDefault()
      }
    }
    target.addEventListener("touchmove", disablePinchZoom, { passive: false })
    return () => {
      target.removeEventListener("touchmove", disablePinchZoom)
    }
  }, [])
  return <div ref={ref}>{children}</div>
}

reference: https://stackoverflow.com/questions/49500339/cant-prevent-touchmove-from-scrolling-window-on-ios?noredirect=1&lq=1

original post(japanese): https://www.terrier.dev/blog/2019/20191103224505-react-hooks-pinch-zoom/

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (1)

Collapse
 
chance_hacker profile image
ChanceTheHacker

Simple and to the point. I love it!

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay