Alex
Alex

Reputation: 1375

How to sort HTML Table in ReactJS

I have array of Objects and I add my data to HTML Table. Now I need to sort my data by version. How can I do something like that in React?

  render() {
    return (
      <div>
        <div>
          <Label> We got {this.state.count} elements in our database. </Label>
        </div>
        <div>
          <Table hover striped bordered responsive size="sm" >
            <thead>
              <tr>
                <th>VERSION</th>
                <th>DATE</th>
                <th>UUID</th>
              </tr>
            </thead>
            <tbody>
              {this.state.results.map(result =>
                <tr key={result.fileId}>
                  <td>{result.VERSION}</td>
                  <td>{result.ORIGIN}</td>
                  <td>{result.UUID}</td>
                </tr>
              )}
            </tbody>
          </Table>
        </div>
      </div>
    );
  }
}

Maybe I can use some js script, but tell me how to use it, I'm new with ReactJS. My version for is 0.26.8 for example.

Upvotes: 2

Views: 5273

Answers (3)

TimoStaudinger
TimoStaudinger

Reputation: 42460

Simply make sure this.state.results is sorted correctly before rendering.


The simplest approach would likely be similar to the following:

  {this.state.results.sort((a, b) => a.VERSION - b.VERSION).map(result =>
    <tr key={result.fileId}>
      <td>{result.VERSION}</td>
      <td>{result.ORIGIN}</td>
      <td>{result.UUID}</td>
    </tr>
  )}

Edit: Since you stated that the version is not a numeric value, but rather a semantic versioning string, your sort function needs to be a bit more complex. I suggest you have a look at this SO question, or use one of the many available libraries covering that use case.

Upvotes: 2

Anthony
Anthony

Reputation: 6482

const sorted = results.sort((x,y) => {
    return parseInt(x.VERSION) - parseInt(y.VERSION);
});

sorts in Ascending order

Upvotes: 1

Max Millington
Max Millington

Reputation: 4498

I would use lodash's sortBy() function here:

https://lodash.com/docs/4.17.4#sortBy

const sorted = _.sortBy(this.state.results, 'VERSION')

Then map over sorted instead of the this.state.results

Upvotes: 3

Related Questions