Enhancing Charts with Interactive Zoom Feature
Showcase how to implement an interactive zoom feature in a chart using TanStack React Charts and React's useState and useEffect hooks for managing zoom state and effects.
import React, { useState, useEffect } from 'react';
import { Chart } from 'react-charts';
Imports React along with useState and useEffect hooks, and the Chart component from react-charts.
function ZoomableChart({ data }) {
const [zoom, setZoom] = useState({ scaleX: 1, scaleY: 1 });
Defines the ZoomableChart component with data prop. Initializes zoom state for X and Y axis scaling.
useEffect(() => {
// Assuming an external source to listen to zoom changes
const onZoomChange = (newZoom) => {
setZoom(newZoom);
};
// Example subscribe function
subscribeToZoom(onZoomChange);
return () => {
// Unsubscribe to avoid memory leaks
unsubscribeToZoom(onZoomChange);
};
}, []);
Sets up an effect to subscribe to zoom changes from an external source and clean up on component unmount.
const handleZoomIn = () => {
setZoom(prevZoom => ({ scaleX: prevZoom.scaleX * 1.1, scaleY: prevZoom.scaleY * 1.1 }));
};
Function to handle zoom in action by increasing both scaleX and scaleY by 10%.
const handleZoomOut = () => {
setZoom(prevZoom => ({ scaleX: prevZoom.scaleX * 0.9, scaleY: prevZoom.scaleY * 0.9 }));
};
Function to handle zoom out action by decreasing both scaleX and scaleY by 10%.
// Adjust the axes and series according to the zoom state
const axes = [{ primary: true, type: 'linear', position: 'bottom', scale: zoom.scaleX },
{ type: 'linear', position: 'left', scale: zoom.scaleY }];
Configures chart axes to adapt to current zoom state.
return (
<div>
<button onClick={handleZoomIn}>Zoom In</button>
<button onClick={handleZoomOut}>Zoom Out</button>
<Chart data={data} axes={axes} />
</div>
);
}
Renders the ZoomableChart component with zoom in and zoom out buttons, and the chart itself adjusted for the current zoom level.
export default ZoomableChart;
Exports the ZoomableChart component for use in other parts of the application.