Adding Zoom and Pan Interactivity to Charts
Enhance a chart with zoom and pan functionality, allowing users to explore data more interactively within TanStack React Charts.
import { Chart } from 'react-charts';
import React, { useState } from 'react';
function MyChart() {
const [zoomState, setZoomState] = useState({ scaleX: 1, scaleY: 1, translateX: 0, translateY: 0 });
const handleZoom = (deltaScale, event) => {
setZoomState(prevState => {
const newScaleX = prevState.scaleX * deltaScale;
const newScaleY = prevState.scaleY * deltaScale;
return { ...prevState, scaleX: newScaleX, scaleY: newScaleY };
});
};
const handlePan = (deltaX, deltaY) => {
setZoomState(prevState => {
const newTranslateX = prevState.translateX + deltaX;
const newTranslateY = prevState.translateY + deltaY;
return { ...prevState, translateX: newTranslateX, translateY: newTranslateY };
});
};
// Add your chart options and data
return (
<div onWheel={(e) => handleZoom(e.deltaY * -0.01, e)}
onMouseMove={(e) => e.buttons === 1 && handlePan(e.movementX, e.movementY)}>
<Chart /* your chart configuration here, injecting zoomState properties as needed */ />
</div>
);
}
This code creates a basic zoom and pan functionality for a React chart using the react-charts library. It utilizes the useState hook to manage the chart's zoom and pan state. The `handleZoom` function updates the scale of the chart based on wheel events, allowing users to zoom in and out. The `handlePan` function updates the translation of the chart based on mouse movement while the left mouse button is pressed, allowing users to pan around. These handlers are attached to the div containing the chart, affecting its transformation properties based on user interactions.