Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a table in ReactJS sortable?

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 the columns of the table sortable. Can someone help me with that. Here is my code.

class ParentComponent extends Component {
  constructor(props) {
    super(props);
    this.state = { data: [] };
  }

  componentDidMount() {
    fetch("http://hostname:xxxx/yyyy/zzzz")
      .then(function(response) {
        return response.json();
      })
      .then(items => this.setState({ data: items }));
  }

  render() {
    var newdata = this.state.data;

    return (
      <table className="m-table">
        <thead>
          <tr>
            <th>AccountName</th>
            <th>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;
like image 989
Midhun Mathew Sunny Avatar asked Jun 05 '17 18:06

Midhun Mathew Sunny


People also ask

How do I make a table sortable?

How to Make Sortable Tables. Adding the "sortable" class to a <table> element provides support for sorting by column value. Clicking the column headers will sort the table rows by that column's value. Tables must use <thead> and <th> tags for sortable functionality to work.

How add sort in react JS?

The Grid component supports sorting data by one or several column values. Use the corresponding plugins and UI (column headers and Group Panel) to manage the sorting state and sort data programmatically. Click several columns while holding Shift to sort data by these columns.

How do you use sortable in react?

React Sortable HOC supports keyboard sorting out of the box. To enable it, make sure your SortableElement or SortableHandle is focusable. This can be done by setting tabIndex={0} on the outermost HTML node rendered by the component you're enhancing with SortableElement or SortableHandle .


1 Answers

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;
like image 161
Ted Avatar answered Oct 13 '22 05:10

Ted