Sort data in a table
interface User {
firstName: string;
lastName: string;
age: number;
}
const [users, setUsers] = useState<User[]>([]);
useEffect(() => {
const _users: User[] = [
{ firstName: "Christian", lastName: "Batz", age: 18 },
{ firstName: "Brain", lastName: "Wisozk", age: 19 },
{ firstName: "Neha", lastName: "Jones", age: 23 },
{ firstName: "Tristin", lastName: "Buckridge", age: 31 },
];
setUsers(_users);
}, []);
function sortData(event: GoabTableOnSortDetail) {
const _users = [...users];
_users.sort((a: any, b: any) => {<GoabTable onSort={sortData} width="100%">
<thead>
<tr>
<th>
<GoabTableSortHeader name="firstName">First name</GoabTableSortHeader>
</th>
<th>
<GoabTableSortHeader name="lastName">Last name</GoabTableSortHeader>
</th>
<th>
<GoabTableSortHeader name="age" direction="asc">
Age
</GoabTableSortHeader>
</th>
</tr>
</thead>
<tbody>
{users.map((user) => (
<tr key={user.firstName}>
<td>{user.firstName}</td>
<td>{user.lastName}</td>
<td>{user.age}</td>
</tr>
))}
</tbody>
</GoabTable>Enable column sorting in tables using sort headers, allowing workers to organize data by clicking column headers to toggle ascending/descending order.
When to use
Use this pattern when:
- Workers need to organize tabular data by different columns
- Data sets are large enough that sorting improves usability
- Multiple columns could reasonably be used as sort criteria
Considerations
- Indicate the current sort direction with visual cues
- Set a sensible default sort order when the table loads
- Consider which columns should be sortable based on data type
- Numeric columns typically sort numerically, text columns alphabetically
- Maintain sort state when data updates if appropriate