Saleh Mubashar I'm an experienced web developer who uses his knowledge and experience to guide people looking to learn web dev and new technologies.

Adding zoom, pan, and pinch to your React web apps

3 min read 971 104

Zoom Pan Pinch React Web Apps

When creating interactive and responsive user interfaces, including zoom, pan, and pinch features can be useful. For example, imagine an image gallery where users can zoom in on specific details of an image, or a map application that allows users to zoom out to see different regions. In this article, we’ll explore a few libraries that you can use in your React applications to add zoom, pan, and pinch functionalities to HTML elements. Let’s get started!

Jump ahead:

React Zoom Pan Pinch

React Zoom Pan Pinch is one the most popular npm packages for adding zoom, pan, and pinch functionalities to HTML packages. It provides a lot of props, handlers, and hooks that make it possible to create a wide range of interactive elements. To get started, install it by using one of the following respective commands for npm or Yarn:

npm i react-zoom-pan-pinch
yarn add react-zoom-pan-pinch

Next, import TransformWrapper and TransformComponent from the library. The entire component will be wrapped by the TransformWrapper.

There are a many props available to customize the component; some notable ones include setting the initial, maximum, and minimum scale and position,  as well as controlling the mousewheel’s movement, panning, pinching, double click, and touch interactions:

import React from "react"
import { TransformWrapper, TransformComponent } from "react-zoom-pan-pinch";

export const App = () => {
  return (
    <TransformWrapper>
      <TransformComponent>
        <img src="test.jpg" alt="test" />
      </TransformComponent>
    </TransformWrapper>
  );
};

To add zoom, pan, and pinch features to your image, simply implement the code above. With the useControls Hook, you can include manual control buttons for zooming in and out. Lastly, we can reset the image back to its original position and scale using the resetTransform() method.

Make sure that the controls component is called inside of the TransformWrapper; the useControls Hook can only be called within this wrapper:

const Controls = () => {
  const { zoomIn, zoomOut, resetTransform } = useControls();
  return (
    <>
      <button onClick={() => zoomIn()}>Zoom In</button>
      <button onClick={() => zoomOut()}>Zoom Out</button>
      <button onClick={() => resetTransform()}>Reset</button>
    </>
  );
};

In the demo below, we can zoom in and out of our image by using either of the controls at the top, scrolling the mousewheel, or pinching the touchpad. Furthermore, we can pan across the image by simply dragging it. There is also a reset button that can reset the image back to its original position and scale:

react-quick-pinch-zoom

Like React Zoom Pan Pinch, react-quick-pinch-zoom is another helpful library; it allows user to zoom and drag any DOM element by using multi-touch gestures and mouse-events on mobile and desktop applications, respectively. You can install it by using one of the following commands:

npm i react-quick-pinch-zoom
yarn add react-quick-pinch-zoom

To use the react-quick-pinch-zoom library, start by importing QuickPinchZoom and make3dTransformValue. As with the other libraries, we use QuickPinchZoom as a wrapper component for the image.

We use an onUpdate callback function to update the transform values of the image. You can create a ref for the image to apply the updated styles using the make3dTransformValue:

import React, { useCallback, useRef } from "react";
import QuickPinchZoom, { make3dTransformValue } from "react-quick-pinch-zoom";
export default function App() {
  const imgRef = useRef();
  const onUpdate = useCallback(({ x, y, scale }) => {
    const { current: img } = imgRef;
    // check if image exists
    if (img) {
      const value = make3dTransformValue({ x, y, scale });
      img.style.setProperty("transform", value);
    }
  }, []);
  return (
    &lt;QuickPinchZoom onUpdate={onUpdate}>
      <img
        ref={imgRef}
        alt="img"
        src="image.jpg"
      />
    </QuickPinchZoom>
  );
}

To allow for more functionalities like zoom factors, inertia friction, and touch functions, you can add more props to the QuickPinchZoom wrapper:

In the example above, we use multiple props to change factors like the amount of zoom and the responsiveness of the image. We use tapZoomFactor to specify the amount of zoom that occurs on tapping the touchpad or touchscreen. We also specify the max and min zoom factors. You can check out all the available props here.

react-map-interaction

The react-map-interaction library allows you to add actions like zooming and panning to any React element on both touch devices as well as with a mouse or touchpad. To get started, install the library using either of the following commands:

npm i react-map-interaction
yarn add react-map-interaction

To add interactions on a DOM element, import MapInteractionCSS from the library. Like in the previous examples, you can wrap your DOM element with this component. You can create any type of element, like an image, within this component to add the desired features:

import React from "react";
import { MapInteractionCSS } from 'react-map-interaction';

export default function App (){
  return (
    <MapInteractionCSS>
      <img src="image.jpg" />
    </MapInteractionCSS>
  );
}

To control the behavior of the component, we can use several notable props, like translationBounds to limit translation in any direction, min/max scale to set the allowable range of scaling, and defaultValue to specify the initial scale and position of the element.

We can also add controls with the showControls prop and customize the content of the buttons with plusBtnContents and minusBtnContents. Lastly, you can apply custom classes to these controls for further styling options. Below is a demo:

Conclusion

Adding zoom, pan, and pinch functionalities to HTML elements can greatly enhance the interactivity and responsiveness of a React application. In this article, we explored three libraries that can assist in implementing these features: React Zoom Pan Pinch, react-quick-pinch-zoom, and react-map-interaction.

These libraries provide a wide range of customization options, allowing you to create an interactive component exactly how you want. Although I’ve discussed some of the most popular libraries, there are many others available that might better suit your needs. However, in most cases, the ones I have discussed should be more than enough to fulfill your requirements. Thanks for reading!

Get setup with LogRocket's modern React error tracking in minutes:

  1. Visit https://logrocket.com/signup/ to get an app ID.
  2. Install LogRocket via NPM or script tag. LogRocket.init() must be called client-side, not server-side.
  3. $ npm i --save logrocket 

    // Code:

    import LogRocket from 'logrocket';
    LogRocket.init('app/id');
    Add to your HTML:

    <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script>
    <script>window.LogRocket && window.LogRocket.init('app/id');</script>
  4. (Optional) Install plugins for deeper integrations with your stack:
    • Redux middleware
    • ngrx middleware
    • Vuex plugin
Get started now
Saleh Mubashar I'm an experienced web developer who uses his knowledge and experience to guide people looking to learn web dev and new technologies.

Leave a Reply