Blog>
Snippets

Integrating Sortable Columns in a Virtual Table

Show how to add sortable columns to a virtualized table created with TanStack Virtual, including the setup of event handlers for column headers to trigger sorting operations and re-rendering of the table data based on the selected sort order.
const [data, setData] = useState(originalData);
Initialize state for your table data.
const [sortBy, setSortBy] = useState(null);
Keep track of the current sort column and direction.
const sortData = (field) => {
  const sortedData = [...data].sort((a, b) => {
    if (a[field] < b[field]) return sortBy === 'ASC' ? -1 : 1;
    if (a[field] > b[field]) return sortBy === 'ASC' ? 1 : -1;
    return 0;
  });
  setData(sortedData);
  // Toggle sort direction
  setSortBy(sortBy === 'ASC' ? 'DESC' : 'ASC');
};
Function to sort the data based on the selected column field and toggle sort direction.
const handleSort = (field) => () => {
  sortData(field);
};
Wrapper function for sortData to be used as click handler with closure to remember the field.
<div>{headers.map(header => (
  <div onClick={handleSort(header.field)}>{header.name}</div>
))}</div>
Render column headers with click event listeners for sorting. Replace this JSX code into your component's return statement where you render the table headers.