简体   繁体   中英

How to sort react-bootstrap Table component

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?

我建议使用react-bootstrap-table然后使用这些示例

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM