Cory Allen
Cory Allen

Reputation: 159

Sort table asc/des in React

I have this table I am working with. So far, when the "Date" column get's clicked, it sorts the table in ascending order just fine. I would like to be able to click it again and have it return to descending order. Any idea on how to do it?

I know that just switching my a and b in sortBy after the => will do the opposite.

class Orders extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        data: [
          {orders: 'Vanilla', date: '03/15/1990'}, 
          {orders: 'Chocolate', date: '03/15/1989'}, 
        ],
      };

      this.sortBy.bind(this);
    }

    renderTableData() {
        return this.state.data.map((data, index) => {
            const{orders, date} = data
            return (
                <tr key={index}>
                   <td>{orders}</td> 
                   <td>{date}</td>
                </tr>
            )
        })
    } 

    sortBy(sortedKey) {
        const data = this.state.data;
        data.sort((a,b) => a[sortedKey].localeCompare(b[sortedKey]))
        this.setState({data})
    }

    render() {
      let newData = this.state.data;

      return (
        <table id="orders">

          <tr className="header">
            <th>Order</th>
            <th onClick={() => this.sortBy('date')}>Date</th>
          </tr>
          <tbody>
            {this.renderTableData()}
          </tbody>
        </table>
      );

    }
  }

  export default Orders;  

Upvotes: 1

Views: 512

Answers (2)

Jatin Parmar
Jatin Parmar

Reputation: 2900

first thing you should maintain the sorting order in state:

  this.state = {
    sortingOrder:'DESC',
    data: [
      {orders: 'Vanilla', date: '03/15/1990'}, 
      {orders: 'Chocolate', date: '03/15/1989'}, 
    ],
  };

after each sorting you should alter it in your sort function

sortBy(sortedKey) {
    const data = this.state.data;
    let sortingOrder=this.state.sortingOrder;

    if(sortingOrder==='ASC'){
      sortingOrder='DESC';
      data.sort((a,b) => b[sortedKey].localeCompare(a[sortedKey]))
    }else{
      sortingOrder='ASC';
      data.sort((a,b) => a[sortedKey].localeCompare(b[sortedKey]))
    }
    this.setState({data,sortingOrder});
}

inorder to do initial sorting by ascending order you should call sort by on componentDidMount method,note that i have changed ASC to DESC as initial value

 componentDidMount(){
           this.sortBy('date');
 }

Upvotes: 2

uday
uday

Reputation: 1481

Just add another state variable which is boolean and based on that switch the order. Something like this sample

Upvotes: 1

Related Questions