How to get the selected value from a dropdown in React

React is a popular JavaScript library for building web applications. It helps create interactive applications.

When users interact with form elements such as <input>, <textarea>, and <select>, they change the value of the element on each interaction. In React, this mutable value is stored in the state property of components and is only updated using setState().

The <select> and <option> elements are used to create a dropdown menu, this menu reveals a list of options when a user interacts with it. We’ll learn to retrieve the selected value from a dropdown in React.

How React handles form state

When developing a React application, it is recommended to let a React component handle form data. The following are the two types of components:

  • Uncontrolled components

  • Controlled components

Uncontrolled dropdown component

An uncontrolled component is a component that is not controlled by React state. Its value is handled by the DOM (Document Object Model).

Coding example

Let’s look at a coding example to learn more about this:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);
Uncontrolled dropdown component

Explanation

  • Line 1: We import React.

  • Lines 314: We create a regular dropdown component whose state is not controlled by React.

Controlled dropdown component

A controlled component is one whose state controls how the component handles form data. This component renders a form, and as a user interacts with this form, the data inputted is controlled by the form's state.

Coding example

Let’s look at a coding example to learn more about this:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);
Controlled dropdown component

Explanation

  • Line 1: We import React.

  • Lines 37: We add a base constructor with props that assigns the initial this.state to {selectValue: ‘’}.

  • Lines 911: We create a handleChange method that will be triggered whenever the component’s state changes. This method receives the event object and uses this.setState() to update the value of the component state.

  • Lines 1321: We render the dropdown component and add this.handleChange as an event handler in the onChange listener of the select element. Every time the state changes, the event handler is triggered, and the state is updated.

Free Resources