Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an array as option for react select component

Tags:

select

reactjs

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> 
like image 416
bluelabelz Avatar asked Jul 14 '15 17:07

bluelabelz


People also ask

How do you select the value of an array in React?

To generate option tags for a select from an array in React: Use the map() method to iterate over the array. On each iteration, return an option element. Pass a unique key prop to each option element.

How do you pass an array to another component in React?

To pass an array as a prop to a component in React, wrap the array in curly braces, e.g. <Books arr={['A', 'B', 'C']} /> . The child component can perform custom logic on the array or use the map() method to render the array's elements. Copied!

How do you get selected options in React-select?

To fetch the selected value from the select element, you can use the onChange event handler prop. Just like the input or textarea elements, you can use the onChange event handler to get the value from the event object. Now, make this select input element controlled by using the state to pass the value.

Can you have an array of React components?

To render an array of components in React you simply need to pass the array into JSX by wrapping it in curly braces, just be sure that your components each have a unique key prop because React will use this when rendering it to avoid bugs.


2 Answers

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>; 
like image 193
John Haugeland Avatar answered Sep 20 '22 20:09

John Haugeland


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> 
like image 25
The Coder Avatar answered Sep 19 '22 20:09

The Coder