Blog>
Snippets

Configuring TanStack React Chart for Responsiveness

Demonstrate how to set up a responsive chart using TanStack React Charts by detecting container size changes with `useEffect` and adjusting chart dimensions.
import React, { useState, useEffect, useRef } from 'react';
import { useChart } from 'tanstack-react-charts';
Imports React hooks needed for the component, as well as the useChart hook from TanStack React Charts.
const ResponsiveChart = () => {
  const chartContainerRef = useRef(null);
  const [chartSize, setChartSize] = useState({ width: 0, height: 0 });
Defines the ResponsiveChart component, initializes a ref to track the chart container DOM element, and a state to hold its size.
useEffect(() => {
    const handleResize = () => {
        if (chartContainerRef.current) {
            setChartSize({
                width: chartContainerRef.current.offsetWidth,
                height: chartContainerRef.current.offsetHeight
            });
        }
    };
    window.addEventListener('resize', handleResize);
    handleResize();
    return () => window.removeEventListener('resize', handleResize);
}, []);
Sets up an effect to handle window resize events. On resize, updates the chartSize state with the current dimensions of the chart container. Cleans up by removing the event listener.
const { getChartProps } = useChart({
    options: {
        width: chartSize.width,
        height: chartSize.height
    }
});
Utilizes the useChart hook from TanStack React Charts to set up the chart props, dynamically adjusting its width and height based on the current state.
return (
    <div ref={chartContainerRef} style={{width: '100%', height: '100%'}}>
        {/* Render your chart using getChartProps() here */}
    </div>
);
Renders the chart container div, using the ref to allow measurement of its dimensions. The actual chart would be rendered inside this div, configured with props from getChartProps().
};

export default ResponsiveChart;
Closes the ResponsiveChart component definition and exports it for use elsewhere in the application.