-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsortTableData.js
More file actions
41 lines (35 loc) · 894 Bytes
/
Copy pathsortTableData.js
File metadata and controls
41 lines (35 loc) · 894 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { useState } from "react";
const usersData = [
{ id: 1, name: "Lalit", age: 30 },
{ id: 2, name: "Amit", age: 25 },
{ id: 3, name: "Priya", age: 28 },
];
export default function SortTable() {
const [users, setUsers] = useState(usersData);
const [order, setOrder] = useState("asc");
const sortByAge = () => {
const sorted = [...users].sort((a, b) => {
return order === "asc" ? a.age - b.age : b.age - a.age;
});
setUsers(sorted);
setOrder((prev) => (prev === "asc" ? "desc" : "asc"));
};
return (
<table border="1">
<thead>
<tr>
<th>Name</th>
<th onClick={sortByAge}>Age</th>
</tr>
</thead>
<tbody>
{users.map((user) => (
<tr key={user.id}>
<td>{user.name}</td>
<td>{user.age}</td>
</tr>
))}
</tbody>
</table>
);
}