DEV Community

terrierscript
terrierscript

Posted on

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/

Top comments (1)

Collapse
 
chance_hacker profile image
ChanceTheHacker

Simple and to the point. I love it!