Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JS sort by ascending and descending

Tags:

reactjs

lodash

I've been using sortBy from lodash, but keep getting

./src/components/Product.js
Syntax error: Unexpected token (17:29)

  15 |       sortByPrice() {
  16 |         this.setState(prevState => ({
> 17 |           sortBy(prevState, ['price'])
     |                              ^
  18 |         }));
  19 |       }
  20 |

This is my component, in which I want to sort the array of objects based on their price. this.state inside return() gives me an array, so that seems to be working, I just need to get the sortByPrice() working

import React, { Component } from 'react'
import sortBy from 'lodash/sortBy'
import './Product.css'
import products from '../offers.json'


class Product extends Component {

  constructor(props) {
    super(props)
    this.state = { products }
    this.sortByPrice = this.sortByPrice.bind(this);
  }

  sortByPrice() {
    this.setState(prevState => ({
      sortBy(prevState, ['price'])
    }));
  }

  render() {
    return (
      <div className="Product">
      <a href="#" onClick={this.sortByPrice}>
      Click me
      </a>
      <br />
      { products.map((product, index) =>
        <div key ={index} className="card">
        <img src={ product.product.details.image } alt={ product.product.details.ean }/>
        <h3>Prijs: { product.price } Euro</h3>
        <p>Staat: { product.description }</p>
        <p>Verkoper: { product.user.details.firstname }</p>
        </div>
      )}
      </div>
    )
  }
}
export default Product

UPDATE

Turns out I was trying to call sortBy() on and object, which resulted in the error. Implemented this and the errors went away, now I just need to figure out a way to manage my state and re-render the view

this.setState(prevState => {
    { products: sortBy(prevState.products, ['price']) }
});

UPDATE 2

After talking to some friends I was advised to ditch lodash for this altogether. I just wrote the functions myself, added my binds to the constructor and called my functions in the onClick of my ASC and DESC buttons.

import React, { Component } from 'react'
import './Product.css'
import products from '../offers.json'

class Product extends Component {

  constructor(props) {
    super(props)
    this.state = { products }
    this.sortByPriceAsc = this.sortByPriceAsc.bind(this);
    this.sortByPriceDesc = this.sortByPriceDesc.bind(this);
  }

  sortByPriceAsc() {
    this.setState(prevState => {
      this.state.products.sort((a, b) => (a.price - b.price))
  });
  }

  sortByPriceDesc() {
    this.setState(prevState => {
      this.state.products.sort((a, b) => (b.price - a.price))
  });
  }

  render() {
    return (
      <div>
      Sorteren:
        <button onClick={this.sortByPriceAsc}>
          ASC
        </button>
        <button onClick={this.sortByPriceDesc}>
          DESC
        </button>
      <div className="product">
      { this.state.products.map((product, index) =>
        <div key ={index} className="card">
          <img src={ product.product.details.image } alt={ product.product.details.ean }/>
          <h3>Prijs: { product.price } Euro</h3>
          <p>Staat: { product.description }</p>
          <p>Verkoper: { product.user.details.firstname }</p>
        </div>
      )}
      </div>
      </div>
    )
  }
}
export default Product
like image 488
Florestan Korp Avatar asked Jun 14 '17 05:06

Florestan Korp


People also ask

How do I sort API data in react JS?

sort((a, b) => b[sortProperty] - a[sortProperty]); setData(sorted); }; sortArray(sortType); here we select the type based on sort type and use the sort function the compares the consecutive data based on the same property and store the changes in data and will be displayed in react-dom.


2 Answers

WORKING CODE:

    import React, { Component } from 'react'
    import './Product.css'
    import products from '../offers.json'

    class Product extends Component {

      constructor(props) {
        super(props)
        this.state = { products }
        this.sortByPriceAsc = this.sortByPriceAsc.bind(this);
        this.sortByPriceDesc = this.sortByPriceDesc.bind(this);
      }

      sortByPriceAsc() {
        this.setState(prevState => {
          this.state.products.sort((a, b) => (a.price - b.price))
      });
      }

      sortByPriceDesc() {
        this.setState(prevState => {
          this.state.products.sort((a, b) => (b.price - a.price))
      });
      }

      render() {
        return (
          <div>
          Sorteren:
            <button onClick={this.sortByPriceAsc}>
            Aflopend
            </button>
            <button onClick={this.sortByPriceDesc}>
            Oplopend
            </button>
          <div className="Product">
          { this.state.products.map((product, index) =>
            <div key ={index} className="card">
              <img src={ product.product.details.image } alt={ product.product.details.ean }/>
              <h3>Prijs: { product.price } Euro</h3>
              <p>Staat: { product.description }</p>
              <p>Verkoper: { product.user.details.firstname }</p>
            </div>
          )}
          </div>
          </div>
        )
      }
    }
    export default Product
like image 166
Florestan Korp Avatar answered Nov 15 '22 08:11

Florestan Korp


Sorting an array in ascending and descending order of price-

      sortByPriceAsc=()=>{

          let sortedProductsAsc;
          sortedProductsAsc= this.state.products.sort((a,b)=>{
             return parseInt(a.price)  - parseInt(b.price);
          })

          this.setState({
              products:sortedProductsAsc
          })
      }


      sortByPriceDsc=()=>{

          let sortedProductsDsc;
          sortedProductsDsc= this.state.products.sort((a,b)=>{
             return parseInt(b.price)  - parseInt(a.price);
          })

          this.setState({
              products:sortedProductsDsc
          })
      }
like image 31
Deepak Kumrawat Avatar answered Nov 15 '22 07:11

Deepak Kumrawat