Generate Option tags for Select from an Array in React

avatar

Borislav Hadzhiev

Last updated: Apr 18, 2022

banner

Photo from Unsplash

Generate Option tags for Select from an Array in React #

To generate option tags for a select from an array in React:

  1. Use the map() method to iterate over the array.
  2. On each iteration, return an option element.
  3. Pass a unique key prop to each option element.
App.js
const App = () => { const arr = [ {value: '', text: '--Choose an option--'}, {value: 'apple', text: 'Apple 🍏'}, {value: 'banana', text: 'Banana 🍌'}, {value: 'kiwi', text: 'Kiwi 🥝'}, ]; const handleChange = event => { console.log(event.target.value); }; return ( <div> <select onChange={handleChange} name="fruits" id="fruit-select"> {arr.map((option, index) => ( <option key={index} value={option.value}> {option.text} </option> ))} </select> </div> ); }; export default App;

react select option array

We used the Array.map method to iterate over an array and render an option tag for each array element.

The key prop we passed to each option element is used internally by React. It tracks which elements in the array change, so React can only re-render the array elements that have changed.

We used the index from the map() method, however it is better to use a stable value if you have one.

The value property is guaranteed to be unique between all option elements, so we can use it for the key prop.

App.js
const App = () => { const arr = [ {value: '', text: '--Choose an option--'}, {value: 'apple', text: 'Apple 🍏'}, {value: 'banana', text: 'Banana 🍌'}, {value: 'kiwi', text: 'Kiwi 🥝'}, ]; const handleChange = event => { console.log(event.target.value); }; // 👇️ using option.value for key return ( <div> <select onChange={handleChange} name="fruits" id="fruit-select"> {arr.map(option => ( <option key={option.value} value={option.value}> {option.text} </option> ))} </select> </div> ); }; export default App;

Every time the selected value changes, the handleChange function is invoked. You can access the value of the selected option on the event object as event.target.value.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.