43

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>

5 Answers 5

61

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>;
Sign up to request clarification or add additional context in comments.

2 Comments

can you please explain why we are using curly braces after <select>{ }</select> ?
JS expressions embedded in a jsx template must be surrounded with curly braces.
35

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>

Comments

0

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.

Comments

0

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.

Comments

-2

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>)}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.