eibersji
eibersji

Reputation: 1216

ReactJS: Sort Option choices from API

I have a select and it gets the options from the api, and it looks like this:

enter image description here

I want to sort them in ascending form but I don't know how to do that, here is my code

<select className="form-control form-control-sm" name="subscriptions" onChange={this.changeValues}>
    {
    this.state.variantsData.subscription_plans.map((item, i) => <option key={i} value={item.uuid}>{item.name}</option>)
    }
</select>

Upvotes: 0

Views: 91

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281646

You could write a function that sorts your data which you can then render. To optimise it further you can memoize this function

sortData = (array) => {
   return array.sort(function(a, b) {
       a.match(/(\d+) months/i)[1] - b.match(/(\d+) months/i)[1]
   })
}

render() {
   const data = this.sortData(this.state.variantsData.subscription_plan);
   return (
       <select className="form-control form-control-sm" name="subscriptions" onChange={this.changeValues}>
          {this.state.variantsData.subscription_plans.map((item, i) => (
              <option key={i} value={item.uuid}>{item.name}</option>
          ))
          }
       </select>
   ) 
}

Upvotes: 2

Related Questions