Understanding Forms in React
Forms are one of the most common ways users interact with web applications. Whether it's a login page, registration form, search bar, or contact form, React provides a simple and efficient way to handle form data.
What is a Form in React?
A form is used to collect user input. In React, form elements such as <input>, <textarea>, and <select> are typically controlled using state.
Example:
function LoginForm() {
const [username, setUsername] = useState("");
return (
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Enter username"
/>
);
}
In this example:
-
valueconnects the input to React state. -
onChangeupdates the state whenever the user types. - React becomes the single source of truth for the input value.
Controlled Components
A controlled component is an input element whose value is controlled by React state.
import { useState } from "react";
function Form() {
const [name, setName] = useState("");
return (
<input
value={name}
onChange={(e) => setName(e.target.value)}
/>
);
}
How It Works
- User types in the input.
-
onChangeevent fires. - State updates using
setName. - Component re-renders.
- Input displays the latest state value.
Flow:
User Input
↓
onChange Event
↓
State Update
↓
Re-render
↓
Updated UI
Handling Multiple Inputs
Instead of creating separate states for every field, use a single object.
import { useState } from "react";
function RegisterForm() {
const [formData, setFormData] = useState({
name: "",
email: ""
});
const handleChange = (e) => {
setFormData({
...formData,
[e.target.name]: e.target.value
});
};
return (
<>
<input
name="name"
value={formData.name}
onChange={handleChange}
placeholder="Name"
/>
<input
name="email"
value={formData.email}
onChange={handleChange}
placeholder="Email"
/>
</>
);
}
Why Use [e.target.name]?
[e.target.name]: e.target.value
This dynamically updates the field that triggered the event.
If:
e.target.name = "email"
then:
{
email: "arul@example.com"
}
gets updated automatically.
Form Submission
Use the onSubmit event on the form.
function LoginForm() {
const [email, setEmail] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
console.log(email);
};
return (
<form onSubmit={handleSubmit}>
<input
value={email}
onChange={(e) =>
setEmail(e.target.value)
}
/>
<button type="submit">
Submit
</button>
</form>
);
}
Why preventDefault()?
By default, submitting a form refreshes the page.
e.preventDefault();
prevents the page reload and allows React to handle the submission.
Handling Checkboxes
const [isChecked, setIsChecked] =
useState(false);
<input
type="checkbox"
checked={isChecked}
onChange={(e) =>
setIsChecked(e.target.checked)
}
/>
For checkboxes, use:
e.target.checked
instead of:
e.target.value
Handling Select Dropdowns
const [country, setCountry] =
useState("");
<select
value={country}
onChange={(e) =>
setCountry(e.target.value)
}
>
<option value="">Select</option>
<option value="India">India</option>
<option value="USA">USA</option>
</select>
Basic Form Validation
const handleSubmit = (e) => {
e.preventDefault();
if (!email) {
alert("Email is required");
return;
}
console.log("Form Submitted");
};
Common validations:
- Required fields
- Email format
- Password length
- Confirm password matching
Controlled vs Uncontrolled Components
Controlled Component
<input
value={name}
onChange={(e) =>
setName(e.target.value)
}
/>
- Managed by React state
- Easier validation
- Preferred approach
Uncontrolled Component
const inputRef = useRef();
<input ref={inputRef} />
- Managed by the DOM
- Uses refs to access values
- Less common in React applications
Best Practices
Use controlled components
Store related fields in a single state object
Validate before submission
Use meaningful field names
Prevent default form submission
Reuse a common
handleChangefunction
Conclusion
React forms are built around state management. By using controlled components, handling events with onChange, and managing submissions with onSubmit, you can build scalable and maintainable forms.
Key concepts to remember:
- Controlled Components
useStateonChangeonSubmitpreventDefault()- Form Validation
- Handling Multiple Inputs
Mastering forms is a crucial step toward building real-world React applications.
Top comments (0)