Controlled Form in React — Part 1

Muazzam Nashat
2 min readApr 5, 2021

Forms in React are similar to the standard HTML forms in terms of syntax. There are two types of forms in React: controlled and uncontrolled. In controlled form, we store the data in the state, and the form derives its input values from the state. But in uncontrolled form, we do not store any data in the state. In this article, I am going to explain how we can use the controlled form in React.

For each input, we will need a corresponding state to store the input value and a function to handle the input change and update the store accordingly.

I’ll use a simple form to explain it.

We know that the onChange event handler runs on every keystroke. So, I created a function named “handleChange” and set it to the onChange attribute. As a result, whenever a user presses a key, the “handleChange” function will be invoked.

If we look at the “handleChange” function, we can see that this function is updating the state variables according to the use input. On the other hand, the value attributes of the input components are set to the state variable. As a result, when a user types something, it is assigned to the state variable, and the value is changed accordingly. So, users see whatever they type in their input boxes.

Now the final step is submitting the form.

I have created a function, “handleSubmit,” which prints the state variables when the form is submitted. In a real-world scenario, you’ll make an API call and save the form data.

--

--

Muazzam Nashat

Full stack developer experienced in Ruby and JavaScript based programming.