DEV Community

Cover image for Populate Dropdown Options in React
Anthony DiPietrantonio
Anthony DiPietrantonio

Posted on

Populate Dropdown Options in React

When I first started learning React — I remember struggling to figure out what the necessary logic would be to create a dropdown based on items from an array or object. While it is very straight forward to me now, I'm sure I won't be the last person to have that initial struggle when first building an app with React that needs a dropdown like that. The goal of this post is to help those who may need it in the future.

This post will go over a simple scenario on how to create and dynamically populate dropdown options based on data in an array. This post assumes that you have a general idea of how React works as well as knowledge about React Hooks — specifically useState

The Situation

We have an array which contains some type of data — whether it is hard coded values or values that came from an external source, like an API.

The Goal

We want to take each value in that fruits array and turn it into an option within a dropdown menu. Then display that selected option above the dropdown.

The Starter Code

We have a simple React app / component that has:

  • an array of objects — each representing a fruit — with keys for its value (what we actually want React to use/show us after selecting it) and its label (what we'll see in the dropdown list options).
  • a piece of state — that we'll use to display our selection
  • a handleFruitChange function on the select element so that we can update state after the selection changes
  • the default / starting option in our dropdown
import React, {useState} from 'react';
import './App.css';

function App() {
  // Array of objects containing our fruit data
  let fruits = [
    { label: "Apple", value: "🍎" },
    { label: "Banana", value: "🍌" },
    { label: "Orange", value: "🍊" }
]

// Using state to keep track of what the selected fruit is
let [fruit, setFruit] = useState("⬇️ Select a fruit ⬇️")

// Using this function to update the state of fruit
// whenever a new option is selected from the dropdown
let handleFruitChange = (e) => {
  setFruit(e.target.value)
}

  return (
    <div className="App">
    {/* Displaying the value of fruit */}
    {fruit}
    <br />

    {/* Creating our dropdown and passing it the handleFruitChange 
      so that every time a new choice is selected, our fruit state 
      updates and renders an emoji of the fruit.
    */}
    <select onChange={handleFruitChange}> 
        {/* Creating the default / starting option for our 
          dropdown.
         */}
      <option value="⬇️ Select a fruit ⬇️"> -- Select a fruit -- </option>
    </select>

    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Populating the Dropdown

Now that we have the basic layout of our app and the very beginning of our dropdown — we'll need to go through each object in the fruits array and create an option element for it, with the corresponding value / label.

import React, {useState} from 'react';
import './App.css';

function App() {
  // Array of objects containing our fruit data
  let fruits = [
    { label: "Apple", value: "🍎" },
    { label: "Banana", value: "🍌" },
    { label: "Orange", value: "🍊" }
]

// Using state to keep track of what the selected fruit is
let [fruit, setFruit] = useState("⬇️ Select a fruit ⬇️")

// Using this function to update the state of fruit
// whenever a new option is selected from the dropdown
let handleFruitChange = (e) => {
  setFruit(e.target.value)
}

  return (
    <div className="App">
    {/* Displaying the value of fruit */}
    {fruit}
    <br />

    <select onChange={handleFruitChange}> 
      <option value="⬇️ Select a fruit ⬇️"> -- Select a fruit -- </option>
            {/* Mapping through each fruit object in our fruits array
          and returning an option element with the appropriate attributes / values.
         */}
      {fruits.map((fruit) => <option value={fruit.value}>{fruit.label}</option>)}
    </select>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Now our dropdown will include an option for each fruit in our fruits array. After selecting one, it'll display above the dropdown.

Note: This code would give you a warning in console because we did not give the option a key (which React wants for list items). To get rid of the warning you'd simply update the code to look like this:

{fruits.map((fruit) => <option key={fruit.label} value={fruit.value}>{fruit.label}</option>)}
Enter fullscreen mode Exit fullscreen mode

And thats that! You can view the live demo of this and explore the code yourself on this Replit.

Feel free to reach out here or on my socials for any questions, suggestions, or to say hello 👋

Top comments (5)

Collapse
 
myworldbox profile image
VL

epic code bro

Collapse
 
markscholes profile image
mark-scholes

Thank you for this. I wonder if you could help me understand how you would expand on this. I am trying to populate multiple dropdowns based on what the user selects. So what you have done here is the first step but how would I go about populating the other dropdowns based on the choice from the first. Say for example you have an object of products. Each has a make, model, color, and feature set. I thought it would be simple to automatically populate the next select with the options for that first choice but I'm finding it a challenge.

Collapse
 
dathq profile image
dathq

tks, code pro

Collapse
 
russf profile image
russferns@gmail.com

Beautiful simple explanation for everyone. Thanks;

Collapse
 
danielchochlinski profile image
danielchochlinski

hey, im fetching my array of objects from mongodb,
then i map it, however i get an error when i select one of my options

".map is not a function"