Sort React Table By Clicking On The Column Header

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

Why am I getting this problem?

By default, rendering a table in React 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]);
Also Read: How to Update ReactJS to the Latest Version Safely and Effectively

4. Update Table Headers

Attach onClick handlers to each <th> and display an arrow for sort direction:
<table>  <thead>     <tr>       {['name', 'age', 'email'].map(col => (         <th key={col} onClick={() => handleSort(col)}>           {col.charAt(0).toUpperCase() + col.slice(1)}           {sortConfig.key === col ? (sortConfig.direction === 'asc' ? ' ▲' : ' ▼') : ''}         </th>       ))}     </tr>   </thead>   <tbody>     {sortedData.map(item => (       <tr key={item.id}>         <td>{item.name}</td>         <td>{item.age}</td>         <td>{item.email}</td>       </tr>     ))}   </tbody> </table>

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.
Related

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…

22 Oct, 2025

Understanding the Problem When building React applications, especially Single Page Applications (SPAs) using React Router, you might expect the page to scroll to the top…

10 Oct, 2025

File Structure (Simplified) When you create a new React app using CRA, your project structure looks like this: my-app/├── public/ │   └── index.html  …

07 Oct, 2025