Blog>
Snippets

Implementing Zoom and Pan Features

Provide code examples for adding interactive zoom and pan capabilities to a geographic chart created with TanStack React Charts, highlighting the use of built-in functions and custom implementations.
import { Chart } from 'react-charts';
import React, { useState } from 'react';
First, import necessary modules from react and react-charts.
function MyChart() {
  const [zoomState, setZoomState] = useState({ scaleX: 1, scaleY: 1, translateX: 0, translateY: 0 });

  const handleZoom = (deltaScale, mouseX, mouseY) => {
    setZoomState(prevState => {
      const newScaleX = prevState.scaleX * deltaScale;
      const newScaleY = prevState.scaleY * deltaScale;
      const newTranslateX = mouseX - (mouseX - prevState.translateX) * deltaScale;
      const newTranslateY = mouseY - (mouseY - prevState.translateY) * deltaScale;
      return { scaleX: newScaleX, scaleY: newScaleY, translateX: newTranslateX, translateY: newTranslateY };
    });
  };

  const handlePan = (deltaX, deltaY) => {
    setZoomState(prevState => ({
      ...prevState,
      translateX: prevState.translateX + deltaX,
      translateY: prevState.translateY + deltaY
    }));
  };
  // Chart setup and rendering logic here, employing zoomState for transformation
}
Set up a React component with zoom and pan state management. The `handleZoom` and `handlePan` functions update the state to apply zoom and pan transformations.
// Within your render or return statement of MyChart component:
<Chart options={{
  initialWidth: 800,
  initialHeight: 600,
  zoom: true, // Enable zoom feature
  onZoom: (focusedRange) => handleZoom(focusedRange.scale, focusedRange.mouseX, focusedRange.mouseY),
  pan: true, // Enable pan feature
  onPan: (focusedRange) => handlePan(focusedRange.deltaX, focusedRange.deltaY)
  // More chart options and configurations here
}} />
Connect the React Charts `Chart` component with the zoom and pan handlers. This code sets the chart size, enables zoom and pan features, and links them to handling functions.