ReactJs sorting table data
Here I am writing a plain vanilla class with a simple table to display sorting of data on the click of a table column header. At times, we don’t want to use a third-party plugin for the same as they are
- heavy,
- contain a lot of other redundant functions and
- design customization is difficult
Here is the class
import React, { Component } from "react";
class Test extends Component {
handleSort = (param) => {
let stateFlag = { ...this.state.flags };
// Reset all flags
stateFlag.Id = false;
stateFlag.FirstName = false;
stateFlag.LastName = false;
// Set the sort param flag
stateFlag[param] = true;
if (stateFlag[param] !== this.state.flags[param]) {
this.setState({
data: this.state.data.sort(this.GetSortOrder(param)),
flags: stateFlag,
});
} else {
this.setState({
data: this.state.data.reverse(),
});
}
};
//Comparer Function
GetSortOrder(prop) {
return function (a, b) {
if (a[prop] > b[prop]) {
return 1;
} else if (a[prop] < b[prop]) {
return -1;
}
return 0;
};
}
state = {
data: [
{ FirstName: "John", LastName: "Doe", Id: 1 },
{ FirstName: "Robin", LastName: "Mark", Id: 2 },
{ FirstName: "Steve", LastName: "Hurry", Id: 3 },
{ FirstName: "Lisa", LastName: "John", Id: 4 },
{ FirstName: "Mary", LastName: "Dunn", Id: 5 },
{ FirstName: "Alfred", LastName: "Park", Id: 6 },
{ FirstName: "Angel", LastName: "Brown", Id: 7 },
{ FirstName: "Tony", LastName: "Mendes", Id: 8 },
{ FirstName: "Anita", LastName: "Singh", Id: 9 },
{ FirstName: "Robert", LastName: "Murphy", Id: 10 },
],
flags: { Id: false, FirstName: false, LastName: false },
};
render() {
return (
<React.Fragment>
<table className="table">
<thead>
<tr>
<th onClick={() => this.handleSort("Id")}>ID</th>
<th onClick={() => this.handleSort("FirstName")}>
First Name
</th>
<th onClick={() => this.handleSort("LastName")}>
Last Name
</th>
</tr>
</thead>
<tbody>
<React.Fragment>
{this.state.data.map((items, id) => (
<tr key={"key_" + id}>
<td>{items.Id}</td>
<td>{items.FirstName}</td>
<td>{items.LastName}</td>
</tr>
))}
</React.Fragment>
</tbody>
</table>
</React.Fragment>
);
}
}
export default Test;
Sample output of the class. Sort by ID