Sort React Table By Clicking On The Column Header

This guide shows you how to create user-friendly sortable tables with React and JavaScript.

Summarize with AI

Not enough time? get the key points instantly.

Why am I getting this problem?

By default, rendering a table with ReactJS just displays data in its original order. Clicking the header won’t sort anything unless you explicitly track which column to sort and implement the sorting logic yourself.

Solution

1. Track Sort Configuration

Use useState to hold which column key and sort direction (asc/desc) are active:

const [sortConfig, setSortConfig] = useState({ key: ”, direction: ‘asc’ });

2. Implement the Sorting Function

Create a function that toggles the sort direction for a column or switches to a new column:

const handleSort = (columnKey) => {  setSortConfig(prev => ({

    key: columnKey,

    direction:

      prev.key === columnKey && prev.direction === ‘asc’ ? ‘desc’ : ‘asc’,

  }));

};

3. Sort Data with useEffect or useMemo

Recompute your sorted data whenever the original data or sortConfig changes:

const sortedData = useMemo(() => {  if (!sortConfig.key) return data;

  const sorted = […data].sort((a, b) => {

    if (a[sortConfig.key] < b[sortConfig.key]) return sortConfig.direction === 'asc' ? -1 : 1;

    if (a[sortConfig.key] > b[sortConfig.key]) return sortConfig.direction === ‘asc’ ? 1 : -1;

    return 0;

  });

  return sorted;

}, [data, sortConfig]);

4. Update Table Headers

Attach onClick handlers to each

and display an arrow for sort direction:

  

    

      {[‘name’, ‘age’, ’email’].map(col => (

        

      ))}

    

  

  

    {sortedData.map(item => (

      

        

        

        

      

    ))}

  

handleSort(col)}>

          {col.charAt(0).toUpperCase() + col.slice(1)}

          {sortConfig.key === col ? (sortConfig.direction === ‘asc’ ? ‘ ▲’ : ‘ ▼’) : ”}

        

{item.name} {item.age} {item.email}

Key Takeaways

  • Always store both which column (key) and how (asc/desc) in React state.
  • Use useMemo for performance when sorting arrays.
  • Update sort settings on header clicks to trigger re-render with sorted results.
  • Display icons or arrows to show active sort state.

Resources

Insights from our engineering leaders.

Our team shares practical insights on the technologies and engineering decisions shaping enterprise software today, grounded in real client work.

ReactJS

Filter Items Based On Multiple Properties

Why am I getting this problem? If you apply separate filters in sequence or only check one property at a time your code will match…