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.
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
An uncontrolled component is a component that is not controlled by React state. Its value is handled by the DOM (Document Object Model).
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') );
Line 1: We import React
.
Lines 3–14: We create a regular dropdown component whose state is not controlled by React.
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.
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') );
Line 1: We import React
.
Lines 3–7: We add a base constructor
with props
that assigns the initial this.state
to {selectValue: ‘’}
.
Lines 9–11: 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 13–21: 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.