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')
);
Explanation
Line 1: We import
React.Lines 3–14: 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')
);
Explanation
Line 1: We import
React.Lines 3–7: We add a base
constructorwithpropsthat assigns the initialthis.stateto{selectValue: ‘’}.Lines 9–11: We create a
handleChangemethod that will be triggered whenever the component’s state changes. This method receives theeventobject and usesthis.setState()to update the value of the component state.Lines 13–21: We render the dropdown component and add
this.handleChangeas an event handler in theonChangelistener of theselectelement. Every time the state changes, the event handler is triggered, and the state is updated.