Beginners guide to controlled forms (React)
What is a controlled form?
In React, a form is considered "controlled" when its elements are managed and controlled by the component's state. This means that the form elements, such as input fields and checkboxes, have their values tied to the React state. The value of an element of a controlled form is not just determined by the DOM but rather, it is controlled by the React state.
Why use controlled forms?
With controlled forms, the form element's value always comes from the component's state. This ensures that the form's state remains predictable and in sync with your application's data. You can access, manipulate, or use for any reason, the data of the form with ease, as it's readily available within your component as a state.
Add Logic
Since the information for a form is controlled by a state, you can add logic easily to do things like allow event handlers to set the state only under specific circumstances.
A simple example of this could be if someone needs to type in a phone number in an input field. You can add logic to simply not allow the React state to change unless the user is inputting a number. This would prevent people from accidentally typing in a letter or other symbol. Because your form is controlled the only thing a user will be able to type into that field is a number.
That is a simple straightforward example of how or why you would add logic to a form. Other common things you can do is to only allow letters as input or even making sure the input matches an email address format. I'm sure many of us encounter these examples regularly, and we should keep an eye out to notice them to see how we can use forms in our own applications.
Submit
When you submit a controlled form, you can easily gather all the form data from the component's state, making it convenient to use the data for some sort of API request or any other action, as it has already been prepared, ready for use, nicely in the state.
Testing
Lastly, I will mention that controlled forms are easier to test because you can simulate user interactions by directly manipulating the component's state. This makes it straightforward to write test cases for your form components to make sure everything is functioning properly.
Steps to Using Controlled Forms
Now that we understand the benefits of controlled forms, let's go over how to implement them in React.
1. Initialize State
To create a controlled form, the first thing you need to do is, as you may have guessed, first define a state variable. This holds the values of your form elements. Use the useState hook to initialize your state variable:
import React, { useState } from 'react';
const [formData, setFormData] = useState('');
2. Bind Form Elements to State
Next, you have to bind the value of each form element to the corresponding state variable. For example, if you have an input field, you would set its value to whatever the state variable is:
<input
type="text"
value={formData}
onChange={handleFormChange}
/>
3. Handle Events
Now, you need to define event handler functions that update the state variable when the user interacts with the form element. For instance, if you have an input field, you'll create an onChange event handler that references the function to trigger when the user is attempting to change the value:
function handleFormChange(event){
setFormData(event.target.value);
};
The event handler takes the new value from the event object and sets it as the new state variable. This ensures that the form element's value is always in sync with the component's state.
4. Use State Data
Now that you have a form properly controlled, you can access and use the form data as needed within your component. Submit it, use it in a fetch or do anything you want with it as it's easily accessible now that it's in a controlled state.
Put It Together
Let's put all of this into one piece of code to look at (with a couple things to finish the example). It seems simple enough:
import React, { useState } from 'react';
function ControlledForm(){
const [formData, setFormData] = useState('');
function handleFormChange(event){
setFormData(event.target.value);
};
function handleSubmit(e){
e.preventDefault()
//whatever else you wanted to do with the formData
}
return(
<form onSubmit={handleSubmit}>
<h3>{formData}</h3>
<input
type="text"
value={formData}
onChange={handleFormChange}
/>
<input type="submit" value="submit" />
</form>
)
}
export default ControlledForm;
In this example, the input field's value is controlled by the formData state variable. As the user types, the handleFormChange function updates the state. While typing the h3 will change showing you how the formData is changing in real time. When finished, you can submit the form and do whatever it is you need to do with that data in an application.
Conclusion
Controlled forms are a fundamental concept in React that offers numerous benefits. By following the steps outlined here, you can create controlled forms in your React applications, allowing you to build interactive and responsive user interfaces with ease. Go out and practice building this one, or one similar, from the ground up to fully grasp how the controlled form works. It definitely did for me.
Subscribe to my newsletter
Read articles from Alan Stowe directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by