41

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>
Anton Menshov
  • 2,266
  • 14
  • 34
  • 55
bluelabelz
  • 417
  • 1
  • 4
  • 5

3 Answers3

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>;
John Haugeland
  • 9,230
  • 3
  • 37
  • 40
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>
TheRealMrCrowley
  • 976
  • 7
  • 24
The Coder
  • 4,981
  • 2
  • 29
  • 36
-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>)}

Emeka Kalu
  • 25
  • 2