Handling Forms in React

Beza Sirak
3 min readMay 21, 2020

Forms

Forms are one of the most common things to create using react, so I wanted to cover how different types of forms are handled in React.

Controlled Components

In React, <input>, <textarea>, and <select> usually, maintain their own state and changes the input based on the user’s input. This is an uncontrolled component. In React, things that change are usually kept in a state that can be passed down to children as props. Using setState(), you can update the values of the inputs. In HTML, form elements such as

The two states are combined by making the React state the single source of truth. By giving the input value from React state, it no longer uses its internal state instead the state is provided from React. When a user types something in the input field, both the input field and output paragraph are synchronized by React’s state. The input field has become a controlled element and the App component a controlled component. An input whose element value is controlled by React is called a controlled component.

The Text Area Tag

In HTML, a <textarea> the element defines its text by its children:

In React, a <textarea> uses a value attribute instead. This allows us to write a form that uses a <textarea> very similar to a form that uses a single-line input:

The Select Tag

In HTML, <select> creates a drop-down list. For example, this HTML creates a drop-down list of flavors:

Select

In the above picture note that “coconut” is initially selected since it has the selected value.

React uses a value attribute on the root select tag instated of the selected attribute. This is helpful in a controlled component because you only need to update it in one place. For example:

--

--

Beza Sirak

I am a software developer and a certified scrum master whose passion is to solve business problems using technology.