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>
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.
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!
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.
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.
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>;
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With