Reputation: 654
I'm new to React and am using the Table component from react-bootstrap.
I want to sort my table in ascending order of the 'Days Till Expiry' column.
But the Table component doesn't have a sorting property, does anyone know how I could do this?
Upvotes: 7
Views: 24872
Reputation: 41
Personally I did it by adding an onClick event on the header and having said event trigger a sorting function I'd programmed. To ensure the change shows up, I added a state I could just update to render the table whenever I made a change. Here is what it looks like:
<th className ="text-center" onClick= {()=>sortFunction('headerName')}>HeaderName</th>
and here is an abridged version of the function itself:
function sortFunction(col){
switch (col){
case "headerName":
dataArray.sort((a, b)=>{
if(a.attribute>b.attribute){
return 1:-1;
}
if(a.attribute<b.attribute){
return -1;
}
return 0;
});
break;
default:
//you might want to do something as default, I don't
break;
setSort(sort+1);
just keep in mind I declared the state with:
const [sort, setSort] = useState(0);
When comparing two strings, make sure to use localeCompare and not ><. The beauty of using a custom sorting function is you get to choose how things are compared, meaning you can sort however you would like. I also added another variable later to handle the order and swapping the order when sorting the table.
In your case I would do something like:
dataArray.sort((a, b)=>{
if(new Date(a.daysTillExpiry).getTime()>new Date(b.daysTillExpiry).getTime()){
return 1;
}
if(new Date(a.daysTillExpiry).getTime()<new Date(b.daysTillExpiry).getTime()){
return -1;
}
return 0;
});
setSort(sort+1);
Keep in mind I didn't try it specifically for your order so maybe you'll have to reverse the return 1 and return -1 to get the proper ordering.
Upvotes: 4
Reputation: 2289
I would recommend using react-bootstrap-table then use these examples
Upvotes: 5