Blog>
Snippets

Creating Interactive Filters for TanStack React Charts

Show how to add interactive filter controls (e.g., date range, categories) to dynamically query and update the displayed data in a chart.
import { useState } from 'react';
import { useChart } from 'tanstack-react-charts';
First, import useState from React for managing state and useChart from Tanstack React Charts for chart manipulation.
const [dateRange, setDateRange] = useState({ start: '', end: '' });
const [category, setCategory] = useState('');
Initialize state variables for the date range and category filters.
const handleDateChange = (start, end) => {
  setDateRange({ start, end });
  updateChartData();
};
Function to update the date range state and refresh the chart data based on the new date range.
const handleCategoryChange = (newCategory) => {
  setCategory(newCategory);
  updateChartData();
};
Function to update the category state and refresh the chart data based on the new category.
const updateChartData = () => {
  // Fetch new data based on dateRange and category
  // Use fetched data to update the chart
  const filteredData = fetchData({ dateRange, category });
  const chart = useChart();
  chart.setData(filteredData);
};
Function to retrieve and update the chart data based on the current state of date range and category filters.
// Example usage inside component
// <input type='date' onChange={(e) => handleDateChange(e.target.value, dateRange.end)} />
// <input type='date' onChange={(e) => handleDateChange(dateRange.start, e.target.value)} />
// <select onChange={(e) => handleCategoryChange(e.target.value)}>
//   <option value='Category1'>Category1</option>
//   <option value='Category2'>Category2</option>
// </select>
Example HTML for the date range and category inputs. Use these inputs to capture user selections and trigger the corresponding state update functions.