This guide shows you how to create user-friendly sortable tables with React and JavaScript.
Want to enable column-based sorting in your React table?
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
Use useState to hold which column key and sort direction (asc/desc) are active:
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’,
}));
};
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
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>
eSparkBiz is rated 4.9 Stars
Real People, Real Stories
See why 300+ startups & enterprises trust eSparkBiz with their software outsourcingWhy am I getting this problem? By default, Material React Table renders plain text for each cell based on your data accessor. If you supply…
You can’t set CORS response headers from React (client-side). Browsers enforce CORS based on the server, so you must configure your API server or use…
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…
Let’s discuss how our dedicated experts can help.