1

Having a hard time figuring this out, how do I sort this select list alphabetically in React?

<select
  ref="userInput"
  required
  className="form-control"
  value={this.state.make}
  onChange={this.onChangeMake}
>
  {this.state.makes.map(function(make) {
    return (
      <option key={make} value={make}>
        {make}
      </option>
    );
  })}
</select>
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • 2
    Does this answer your question? [Sort array by firstname (alphabetically) in Javascript](https://stackoverflow.com/questions/6712034/sort-array-by-firstname-alphabetically-in-javascript) – dw_ Dec 10 '19 at 14:03
  • You could try `this.state.makes.slice().sort().map(...)` – Tholle Dec 10 '19 at 14:03
  • @Tholle the option shows alphabetically now with this code `this.state.makes.slice().sort().map(function(make)` thanks :) `value={this.state.make}` any idea how to make the value show alphabetically too? – kimstewartca Dec 10 '19 at 14:14
  • @avidrunner I'm not sure what you mean by "make the value show alphabetically too". Do you want to save the option string sorted alphabetically in your component state? – Tholle Dec 10 '19 at 14:27
  • 1
    Verbiage: by "in React" you mean "in JavaScript". React is a UI library; you don't sort in it. – Dave Newton Dec 10 '19 at 14:29
  • @Tholle the options show up alphabetically now when I click the dropdown but it still shows the first entry I have added as the default “value” before clicking the dropdown, rather than showing the first A-Z or even a default value “Add Make” would work fine. Sorry am new to React hope that makes sense – kimstewartca Dec 10 '19 at 14:31
  • If you want a value not in the list, like an "empty" value, then you need to add it. – Dave Newton Dec 10 '19 at 14:59

2 Answers2

0

you can simply use sort function js

<select
ref="userInput"
required
className="form-control"
value={this.state.make}
onChange={this.onChangeMake}
>
{this.state.makes.sort().map(function(make) {
 return (
  <option key={make} value={make}>
    {make}
  </option>
);
})}
</select>
DEEPAK
  • 1,364
  • 10
  • 24
0

Try using this method with sort().

this.state.makes.sort((a,b) => a > b ? 1 : -1).map(function(make) {
 return (
  <option key={make} value={make}>
    {make}
  </option>
  );
});

Source: https://bobbyhadz.com/blog/react-sort-array-of-objects

AbdurrahmanY
  • 809
  • 13
  • 22