Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to Get Selected Value from a Mapped Select Input in React

Aug 11, 2020 • 5 Minute Read

Introduction

Building select input elements is straightforward when working on web projects. But with the emergence of JavaScript frameworks and libraries, building input elements can be a little tricky as you need to think from a data point of view and plan ahead for all the input elements that will be in the app.

In React, all input elements need to be controlled by the state, including the select element. In this guide, you will learn how to get the selected value from a select input in React.

Mapped Select Input

Start by creating an array of objects to use in creating the options for the select input. For this example, create a select input to select a value from a list of fruits.

      const options = [
  {
    label: "Apple",
    value: "apple",
  },
  {
    label: "Mango",
    value: "mango",
  },
  {
    label: "Banana",
    value: "banana",
  },
  {
    label: "Pineapple",
    value: "pineapple",
  },
];
    

You might be wondering why there need to be objects inside the array when you could use a string to create the options. It's because the value of the option doesn't necessarily have to be the same as the label.

Next, using the options array, create a select input inside the App component with the different options. Assign the value property from the object to the value prop of the options element, so that the options are mapped correctly and the value for the select element can be retrieved.

      import React from "react";

const options = [
  {
    label: "Apple",
    value: "apple",
  },
  {
    label: "Mango",
    value: "mango",
  },
  {
    label: "Banana",
    value: "banana",
  },
  {
    label: "Pineapple",
    value: "pineapple",
  },
];

class App extends React.Component {
  render() {
    return (
      <div id="App">
        <div className="select-container">
          <select>
            {options.map((option) => (
              <option value={option.value}>{option.label}</option>
            ))}
          </select>
        </div>
      </div>
    );
  }
}

export default App;
    

Setting the Default Value Using State

To select a default option in React, the selected attribute is used in the option element. In React, though, instead of using the selected attribute, the value prop is used on the root select element. So, you can set a default value by passing the value of the option in the value prop of the select input element. This is very convenient in a controlled component as you only have to update the value in one place.

      class App extends React.Component {
  render() {
    return (
      <div id="App">
        <div className="select-container">
          <select value="banana">
            {options.map((option) => (
              <option value={option.value}>{option.label}</option>
            ))}
          </select>
        </div>
      </div>
    );
  }
}
    

Getting the Selected Value

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. Set the initial value in the state of the component, and in the handleChange method, set the selected value as the new value in the state.

      class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      fruit: "banana",
    };

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    console.log("Fruit Selected!!");
    this.setState({ fruit: e.target.value });
  }

  render() {
    return (
      <div id="App">
        <div className="select-container">
          <select value={this.state.fruit} onChange={this.handleChange}>
            {options.map((option) => (
              <option value={option.value}>{option.label}</option>
            ))}
          </select>
        </div>
      </div>
    );
  }
}

export default App;
    

Conclusion

In this guide, you learned some everyday use cases for the select input element, such as how to get started, how to fetch the selected value, and how to make the select element controlled. There are third-party libraries like react-select that you can use to minimize all the boilerplate code.

That's it from this guide. Keep learning!

Learn More

Check out these React courses from Pluralsight to continue learning:

Gaurav Singhal

Gaurav S.

Guarav is a Data Scientist with a strong background in computer science and mathematics. He has extensive research experience in data structures, statistical data analysis, and mathematical modeling. With a solid background in Web development he works with Python, JAVA, Django, HTML, Struts, Hibernate, Vaadin, Web Scrapping, Angular, and React. His data science skills include Python, Matplotlib, Tensorflows, Pandas, Numpy, Keras, CNN, ANN, NLP, Recommenders, Predictive analysis. He has built systems that have used both basic machine learning algorithms and complex deep neural network. He has worked in many data science projects, some of them are product recommendation, user sentiments, twitter bots, information retrieval, predictive analysis, data mining, image segmentation, SVMs, RandomForest etc.

More about this author