Skip to content

Noverish/react-use-pinch-zoom

Repository files navigation

license npm version npm downloads

Most of the code is from react-pinch-and-zoom

React-Use-Pinch-Zoom

A react hook for pinch-to-zoom gesture interaction.

Demo

Demo Webp

Demo Webpage

Usage

  1. Install this package as dependency
$ npm install react-use-pinch-zoom
  1. Import the hook, get container and content props from hook, and use them to whatever you want to pinch zoom
import usePinchZoom from 'react-use-pinch-zoom';

function App() {
  const [containerProps, contentProps] = usePinchZoom<HTMLDivElement, HTMLImageElement>();

  return (
    <>
      <h1>Pinch Zoom</h1>
      <div {...containerProps}>
        <img src="/image.jpg" {...contentProps} />
      </div>
    </>
  );
}
  1. [Optional] You can customize style of element.
import usePinchZoom from 'react-use-pinch-zoom';

function App() {
  const [containerProps, contentProps] = usePinchZoom<HTMLDivElement, HTMLImageElement>();

  const { style: containerStyle, ...restContainerProps } = containerProps;

  const newStyle = {
    display: 'inline-block',
    ...containerStyle,
  }

  return (
    <>
      <h1>Pinch Zoom</h1>
      <div style={newStyle} {...restContainerProps}>
        <img src="/image.jpg" {...contentProps} />
      </div>
    </>
  );
}

Options

name Type Default
minZoomScale number 1.0
maxZoomScale number 4.0
onTransform (transform: Transform) => void undefined
import usePinchZoom, { PinchZoomTypes } from 'react-use-pinch-zoom';

const [containerProps, contentProps] = usePinchZoom({
  minZoomScale: 0.5,
  maxZoomScale: 2.0,
  onTransform: (transform: PinchZoomTypes.Transform) => {
    console.log(transform);
  },
});

How it works

containerProps and contentProps consist of below these.

const containerProps = {
  onTouchStart,
  onTouchMove,
  onTouchEnd,
  style: {
    overflow: 'hidden',
    touchAction: 'none',
  },
  ref,
}

const contentProps = {
  style: {
    willChange: 'transform',
    transition: 'transform',

    transform: `scale(${zoomScale}) translate(${x}px, ${y}px)`,
    webkitTransform: `scale(${zoomScale}) translate(${x}px, ${y}px)`,
  },
  ref,
}

react-use-pinch-zoom takes control of touch event and modifies zoomScale, x and y values in transform style string.

Releases

No releases published

Packages

No packages published