7

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. My React App

But the Table component doesn't have a sorting property, does anyone know how I could do this?

2 Answers 2

5

I would recommend using react-bootstrap-table then use these examples

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.