How to make a table in ReactJS sortable?

前端 未结 1 1425
一向
一向 2020-12-30 06:48

I am building a simple app in ReactJS that works with a JSON array by calling a certain API. I am then populating the results of the array in a table. I now wanted to make t

相关标签:
1条回答
  • 2020-12-30 07:38

    Here's a quick example of how to do it, based on my comment:

    class ParentComponent extends Component {
      constructor(props) {
        super(props);
        this.state = { data: [] };
        this.onSort = this.onSort.bind(this)
      }
    
      componentDidMount() {
        fetch("http://hostname:xxxx/yyyy/zzzz")
          .then(function(response) {
            return response.json();
          })
          .then(items => this.setState({ data: items }));
      }
    
      onSort(event, sortKey){
        /*
        assuming your data is something like
        [
          {accountname:'foo', negotiatedcontractvalue:'bar'},
          {accountname:'monkey', negotiatedcontractvalue:'spank'},
          {accountname:'chicken', negotiatedcontractvalue:'dance'},
        ]
        */
        const data = this.state.data;
        data.sort((a,b) => a[sortKey].localeCompare(b[sortKey]))
        this.setState({data})
      }
    
      render() {
        var newdata = this.state.data;
    
        return (
          <table className="m-table">
            <thead>
              <tr>
                <th onClick={e => this.onSort(e, 'accountname')}>AccountName</th>
                <th onClick={e => this.onSort(e, 'negotiatedcontractvalue')}>ContractValue</th>
              </tr>
            </thead>
            <tbody>
              {newdata.map(function(account, index) {
                return (
                  <tr key={index} data-item={account}>
                    <td data-title="Account">{account.accountname}</td>
                    <td data-title="Value">{account.negotiatedcontractvalue}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        );
      }
    }
    
    export default ParentComponent;
    
    0 讨论(0)
提交回复
热议问题