Untitled
unknown
plain_text
3 years ago
3.1 kB
10
Indexable
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import {
Paper,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
TableSortLabel
} from '@material-ui/core';
const useStyles = makeStyles({
table: {
minWidth: 650,
},
});
export default function SortableTable() {
const classes = useStyles();
const [order, setOrder] = React.useState('asc');
const [orderBy, setOrderBy] = React.useState('name');
const handleRequestSort = (event, property) => {
const isAsc = orderBy === property && order === 'asc';
setOrder(isAsc ? 'desc' : 'asc');
setOrderBy(property);
};
const data = [
{ name: 'John Doe', age: 35, address: '123 Main St' },
{ name: 'Jane Smith', age: 28, address: '456 Park Ave' },
// more data here
];
return (
<TableContainer component={Paper}>
<Table className={classes.table} aria-label="sortable table">
<TableHead>
<TableRow>
<TableCell>
<TableSortLabel
active={orderBy === 'name'}
direction={orderBy === 'name' ? order : 'asc'}
onClick={(event) => handleRequestSort(event, 'name')}
>
Name
</TableSortLabel>
</TableCell>
<TableCell align="right">
<TableSortLabel
active={orderBy === 'age'}
direction={orderBy === 'age' ? order : 'asc'}
onClick={(event) => handleRequestSort(event, 'age')}
>
Age
</TableSortLabel>
</TableCell>
<TableCell align="right">
<TableSortLabel
active={orderBy === 'address'}
direction={orderBy === 'address' ? order : 'asc'}
onClick={(event) => handleRequestSort(event, 'address')}
>
Address
</TableSortLabel>
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{data
.sort((a, b) => {
const isAsc = order === 'asc';
switch (orderBy) {
case 'name':
return isAsc
? a.name.localeCompare(b.name)
: b.name.localeCompare(a.name);
case 'age':
return isAsc ? a.age - b.age : b.age - a.age;
case 'address':
return isAsc
? a.address.localeCompare(b.address)
: b.address.localeCompare(a.address);
default:
return 0;
} })
.map((row) => (
<TableRow key={row.name}>
<TableCell component="th" scope="row">
{row.name}
</TableCell>
<TableCell align="right">{row.age}</TableCell>
<TableCell align="right">{row.address}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
);
}
Editor is loading...