bluelabelz
bluelabelz

Reputation: 437

How to use an array as option for react select component

If I wanna replace the options

<option value="A">Apple</option>
<option value="B">Banana</option>

in the given example by the use of an array in a react jsx file, how would I proceed?

<select value="B">
    <option value="A">Apple</option>
    <option value="B">Banana</option>
</select>

Upvotes: 43

Views: 173168

Answers (5)

BDorries
BDorries

Reputation: 21

This is a pretty old question but I just found it and wanted to throw in my two cents. I found several answers helpful and they led me to this answer which works for me. I was trying to populate a dropdown list for a user to select the state they live in. Here is my array of states:

const states = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", "Connecticut", "Delaware", "District of Columbia", "Florida", "Georgia", "Guam", "Hawaii", "Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Puerto Rico", "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"];

And this is the div that contains the select element in my .jsx

<div className="input-field">
                <label htmlFor="addressState">addressState</label>
                <select value={addressState} onChange={(event) => setAddressState(event.target.value)}>
                    {states.map((e,index) => <option key={index} value={e}>{e}</option>
                    )}
                </select>
            </div>

Hope that helps someone

P.S. I called the variable addressState to avoid confusion since React uses the word state a lot.

Upvotes: 0

Colin Keenan
Colin Keenan

Reputation: 1149

I came here looking for a way to use an array as option in a server-side rendered React application. The accepted answer helped me find what works. As an example, given an array of strings called data and a string called selectedOpton (which equals one of the strings in data like data[0]:

            <select value={selectedOption} onChange={function(){}} >
              {data.map( (e) => <option value={e} key={e}>{e}</option> )}
            </select>

I get the chosen result automatically when the form that this is a part of is submitted. Since it's server-side rendered, no javascript is executed after being sent to the browser until the form is submitted. The only reason onChange={function(){}} is included is to supress the illogical error that results from having value={selectedOption}. React insists that if a value is assigned, there must be an onChange defined, even if it's server-side rendered which means the onChange could never be triggered.

Upvotes: 0

John Haugeland
John Haugeland

Reputation: 9668

Because it's just javascript, there are a million ways. The way I usually take is to map the container to generate the guts. A for loop or whatever would also work just fine.

const Answer = react.createClass({

    render: function() {

        var Data     = ['this', 'example', 'isnt', 'funny'],
            MakeItem = function(X) {
                return <option>{X}</option>;
            };


        return <select>{Data.map(MakeItem)}</select>;

    }

};

Or in es6 in more modern react you can just

const Answer = props => 
  <select>{
    props.data.map( (x,y) => 
      <option key={y}>{x}</option> )
  }</select>;

Upvotes: 61

Emeka Kalu
Emeka Kalu

Reputation: 25

You can also abstract your constants into another file and import them.

import {myconstants} from "../constants";

{myconstants.map((x,y) => <option key={y}>{x}</option>)}

Upvotes: -2

The Coder
The Coder

Reputation: 5335

You're usually required to supply a unique key to make sure React can identify items, you can use uuid to do this or a key you have on hand, e.g.

  <Select name={field}>
    {FBButtons.map(fbb =>
      <option key={fbb.key} value={fbb.key}>{fbb.value}</option>
    )};
  </Select>

Upvotes: 35

Related Questions