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/

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
chance_hacker profile image
ChanceTheHacker

Simple and to the point. I love it!

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs