Blog>
Snippets

Making TanStack React Charts Responsive

Demonstrates how to make TanStack React Charts responsive to screen size changes using CSS and React hooks.
import React, { useState, useEffect } from 'react';
import { Chart } from 'tanstack-react-charts';

function ResponsiveChart() {
  const [chartSize, setChartSize] = useState({ width: 300, height: 200 });

  useEffect(() => {
    function handleResize() {
      setChartSize({ width: window.innerWidth * 0.9, height: window.innerHeight * 0.7 });
    }

    window.addEventListener('resize', handleResize);
    handleResize();

    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return <Chart width={chartSize.width} height={chartSize.height} /* other chart props */ />;
}
This code initializes a responsive chart component using TanStack React Charts. It first defines a state 'chartSize' to keep track of the chart's dimensions. The useEffect hook listens for changes in the window's size and updates the chart's size accordingly to maintain a responsive layout. The Chart component's width and height are set using the values from the 'chartSize' state, ensuring the chart resizes dynamically with the browser window.