I've managed to make the table being sorted by each of its columns by clicking on the button next to a column header.
However, I would expect it to sort it reverse alphabetically when it is clicked for the second time and to go back to initial state when it's clicked for the third time.
As it is now it just works for the first click - it sorts it alphabetically - but after that it doesn't do anything no matter how many times it is clicked.
import { Table } from 'semantic-ui-react';
export default class GenericTable extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
currentSort: 'default',
rows: this.props.rows, // the original rows are saved in state
};
}
onSortChange = index => {
let nextSort;
const newRows = this.props.rows.sort(function(a, b) {
if (a.cells[index] < b.cells[index]) {
nextSort = 'up';
return -1;
}
if (a.cells[index] > b.cells[index]) {
nextSort = 'default';
return 1;
}
nextSort = 'down';
return 0;
});
this.setState({ rows: newRows, currentSort: nextSort });
};
render() {
const { currentSort } = this.state; // added state
const sortTypes = { // added constant
up: {
class: 'sort-up',
fn: (a, b) => a.name - b.name,
},
down: {
class: 'sort-down',
fn: (a, b) => b.name - a.name,
},
default: {
class: 'sort',
fn: (a, b) => a,
},
};
const { headers, rows, idList } = this.props;
return (
<Table>
<Table.Header>
<Table.Row>
{headers.map(header => (
<Table.HeaderCell key={headers.indexOf(header)}>
{header}
// added button
<button onClick={() => this.onSortChange(index)} type="button">
<i className={`fas fa-${sortTypes[currentSort].class}`} />
</button>
</Table.HeaderCell>
)}
</Table.Row>
</Table.Header>
<Table.Body>
// added below
{rows.map((row, rowIndex) => (
<Table.Row key={idList && idList[rowIndex]}>
<Table.Cell>
...
</Table.Cell>
</Table.Row>
)}
</Table.Body>
</Table>
);
}
}
I guess something is wrong in onSortChange
but don't know what.