Handling Forms in React
Learn how to handle form input, manage user-entered data, process submissions, and display submitted information in React.
1. Introduction to Handling Forms
Handling forms means collecting information entered by users and deciding what to do with that information. For example, a registration form collects a student's name, email address, and other details.
In React, we commonly use state to store input values and event handlers to respond when users change fields or submit the form.
useState,
onChange, and onSubmit.
2. Creating a Basic Form
A basic form can contain input fields and a submit button. The onSubmit event handler lets the component respond when the user submits the form.
Example
function StudentForm() {
function handleSubmit(event) {
event.preventDefault();
console.log("Form submitted");
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="studentName">
Student Name:
</label>
<input
type="text"
id="studentName"
name="studentName"
/>
<button type="submit">
Submit
</button>
</form>
);
}
export default StudentForm;
Expected Result
Student Form
When the form is submitted in the running React application, "Form submitted" appears in the console.
The event.preventDefault() method prevents the browser's default form submission behavior. The handler can then process the form using React code.
3. Handling Input Changes
The onChange event runs when the value of an input changes. We can use this event to update a state variable with the value entered by the user.
Example
import { useState } from "react";
function NameForm() {
const [name, setName] = useState("");
function handleChange(event) {
setName(event.target.value);
}
return (
<div>
<label htmlFor="name">Name:</label>
<input
type="text"
id="name"
value={name}
onChange={handleChange}
/>
<p>Entered Name: {name}</p>
</div>
);
}
export default NameForm;
Expected Output
Entered Name: Rahul
When the user types "Rahul", the onChange handler updates the name state. React then displays the updated value below the input field.
4. Handling Form Submission
The onSubmit event is triggered when a form is submitted. We can use a handler to read stored form values, validate the information, and perform the required action.
Example
import { useState } from "react";
function LoginForm() {
const [username, setUsername] = useState("");
function handleSubmit(event) {
event.preventDefault();
console.log("Username:", username);
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="username">
Username:
</label>
<input
id="username"
value={username}
onChange={(event) =>
setUsername(event.target.value)
}
/>
<button type="submit">
Login
</button>
</form>
);
}
export default LoginForm;
Expected Console Output
Username: Rahul
If the user enters "Rahul" and submits the form, the handler logs the username stored in state.
5. Handling Multiple Input Fields
A form may contain several input fields. We can store related values in a single state object and update the appropriate property when an input changes.
Example
import { useState } from "react";
function RegistrationForm() {
const [formData, setFormData] = useState({
name: "",
email: ""
});
function handleChange(event) {
const { name, value } = event.target;
setFormData((previousData) => ({
...previousData,
[name]: value
}));
}
function handleSubmit(event) {
event.preventDefault();
console.log(formData);
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="name">Name:</label>
<input
id="name"
name="name"
value={formData.name}
onChange={handleChange}
/>
<label htmlFor="email">Email:</label>
<input
id="email"
name="email"
type="email"
value={formData.email}
onChange={handleChange}
/>
<button type="submit">
Register
</button>
</form>
);
}
export default RegistrationForm;
Expected Console Output
{
name: "Rahul",
email: "rahul@example.com"
}
The name attribute identifies which property should be updated. The spread operator preserves the other values already stored in the state object.
6. Displaying Submitted Form Data
After a form is submitted, we can store the submitted information in state and display it on the page. This is useful for showing a confirmation or summary of the information entered by the user.
Example
import { useState } from "react";
function FeedbackForm() {
const [message, setMessage] = useState("");
const [submittedMessage, setSubmittedMessage] = useState("");
function handleSubmit(event) {
event.preventDefault();
setSubmittedMessage(message);
}
return (
<div>
<form onSubmit={handleSubmit}>
<label htmlFor="message">
Feedback:
</label>
<input
id="message"
value={message}
onChange={(event) =>
setMessage(event.target.value)
}
/>
<button type="submit">
Submit Feedback
</button>
</form>
{submittedMessage && (
<p>
Submitted Feedback: {submittedMessage}
</p>
)}
</div>
);
}
export default FeedbackForm;
Expected Output
Submitted Feedback: Great learning experience!
The submitted message is stored separately from the current input value. After submission, React displays the saved message.
7. Resetting Form Values
After processing a form, we may want to clear the input fields. When form values are controlled by React state, we can reset them by updating the state.
Example
import { useState } from "react";
function CommentForm() {
const [comment, setComment] = useState("");
function handleSubmit(event) {
event.preventDefault();
console.log("Comment:", comment);
setComment("");
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="comment">
Comment:
</label>
<input
id="comment"
value={comment}
onChange={(event) =>
setComment(event.target.value)
}
/>
<button type="submit">
Submit
</button>
</form>
);
}
export default CommentForm;
Expected Result
After submission, the entered comment is logged to the console and the input field becomes empty.
8. Common Mistakes
Mistake 1: Forgetting to Prevent Default Submission
function handleSubmit(event) {
console.log("Form submitted");
}
The browser may perform its default form submission, which can reload or navigate the page.
Correct Code
function handleSubmit(event) {
event.preventDefault();
console.log("Form submitted");
}
Mistake 2: Not Updating the Input State
<input
value={name}
onChange={() => {}}
/>
A controlled input needs an event handler that updates its state value. Otherwise, typing will not update the displayed input value.
Correct Code
<input
value={name}
onChange={(event) =>
setName(event.target.value)
}
/>
Mistake 3: Replacing Other Properties in State
setFormData({
[name]: value
});
This replaces the state object with an object containing only the changed property. Other form values can be lost.
Correct Code
setFormData((previousData) => ({
...previousData,
[name]: value
}));
9. Practice Tasks
Complete these tasks to practise handling forms in React.
Summary
Handling forms in React involves collecting input values, updating state, and processing form submissions using event handlers. The onChange event updates controlled input values, while onSubmit handles the submission process. Multiple input fields can be managed with a state object, submitted information can be displayed using state, and controlled fields can be cleared by resetting their values. These techniques help create interactive forms that can later be extended with validation and server-side processing.