简体   繁体   中英

React : How to sort data in asc and desc in ReactJS

I am showing data through API ( Data is showing in Pagination ) , API were built in Loopback . I want to sort in my project . For example if User click on Table head attribute then It will sort data in asc and desc . I am new ReactJS don't have much knowledge to implement this logic, Could someone please help me to figure out . Thanks

Code

         class Example extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      Item: 5,
      skip: 0
    }

    this.handleClick = this.handleClick.bind(this);
  }

  urlParams() {
    return `http://localhost:3001/meetups?filter[limit]=${(this.state.Item)}&&filter[skip]=${this.state.skip}`
  }

  handleClick() {
    this.setState({skip: this.state.skip + 1})
  }

  render() {
    return (
      <div>
        <a href={this.urlParams()}>Example link</a>
        <pre>{this.urlParams()}</pre>
        <button onClick={this.handleClick}>Change link</button>
      </div>
    )
  }
}


ReactDOM.render(<Example/>, document.querySelector('div#my-example' ))

Let's assume that you fetched your data and now your state looks like this:

state ={
    data : [13,15,21,1,2]
}

Now the work on the server is done, you don't have to fetch new data every time the user click to sort, now just add a function to handle the user click, let's say that the use clicks on the asc order, your handler should look like this:

const clickHandler = order =>{
    switch(order):{
        case 'asc': return this.setState({data : this.state.data.sort((a,b)=> a-b) })

        case 'desc' : return this.setState({data : this.state.data.sort((a,b) => b-a)})
   }

}

semantic-ui-react already support the sort function.

Check this example: https://react.semantic-ui.com/collections/table/#variations-sortable

import _ from 'lodash'
import React, { Component } from 'react'
import { Table } from 'semantic-ui-react'

const tableData = [
  { name: 'John', age: 15, gender: 'Male' },
  { name: 'Amber', age: 40, gender: 'Female' },
  { name: 'Leslie', age: 25, gender: 'Female' },
  { name: 'Ben', age: 70, gender: 'Male' },
]

export default class TableExampleSortable extends Component {
  state = {
    column: null,
    data: tableData,
    direction: null,
  }

  handleSort = clickedColumn => () => {
    const { column, data, direction } = this.state

    if (column !== clickedColumn) {
      this.setState({
        column: clickedColumn,
        data: _.sortBy(data, [clickedColumn]),
        direction: 'ascending',
      })

      return
    }

    this.setState({
      data: data.reverse(),
      direction: direction === 'ascending' ? 'descending' : 'ascending',
    })
  }

  render() {
    const { column, data, direction } = this.state

    return (
      <Table sortable celled fixed>
        <Table.Header>
          <Table.Row>
            <Table.HeaderCell
              sorted={column === 'name' ? direction : null}
              onClick={this.handleSort('name')}
            >
              Name
            </Table.HeaderCell>
            <Table.HeaderCell
              sorted={column === 'age' ? direction : null}
              onClick={this.handleSort('age')}
            >
              Age
            </Table.HeaderCell>
            <Table.HeaderCell
              sorted={column === 'gender' ? direction : null}
              onClick={this.handleSort('gender')}
            >
              Gender
            </Table.HeaderCell>
          </Table.Row>
        </Table.Header>
        <Table.Body>
          {_.map(data, ({ age, gender, name }) => (
            <Table.Row key={name}>
              <Table.Cell>{name}</Table.Cell>
              <Table.Cell>{age}</Table.Cell>
              <Table.Cell>{gender}</Table.Cell>
            </Table.Row>
          ))}
        </Table.Body>
      </Table>
    )
  }
}

To implement this behavior, you must use the "Order filter" for Loopback: https://loopback.io/doc/en/lb3/Order-filter.html

As a result, filter on the "id" field should look something like this:

filter: {"where":{},"order":["id ASC"],"limit":15,"skip":0}

filter: {"where":{},"order":["id DESC"],"limit":15,"skip":0}

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