Introduction
In React, forms are used to collect user input and manage data dynamically. React provides powerful ways to handle form inputs, validations, submissions, and dynamic updates using state management.
React forms are usually controlled using React state. This approach provides better control over user input and makes applications more interactive.
What are React Forms?
React forms are forms created inside React applications to collect and manage user input.
OR
React forms are used to capture and manage user input in React applications.
They allow users to:
- Enter data
- Submit information
- Interact with applications
React forms work similarly to HTML forms but use React state for better control.
Why Forms are Used in React?
Forms are used because users need to interact with applications.
Examples:
- User login
- Registration forms
- Search functionality
- Feedback systems
- Online orders
Without forms, users cannot send or update information.
Basic Form Example in React
function App() {
return (
<form>
<input type="text" />
<button type="submit">
Submit
</button>
</form>
);
}
Controlled Components in React
A controlled component is a form element controlled by React state.
React manages:
- Input value
- Changes
- Updates
Example of Controlled Component
import { useState } from "react";
function App() {
const [name, setName] = useState("");
return (
<div>
<input type="text" value={name} onChange={(e) => setName(e.target.value) } />
<h1>{name}</h1>
</div>
);
}
How Controlled Components Work?
- State stores the input value
- Input displays the state value
- onChange updates state
- React re-renders the UI
Advantages of Controlled Components
- Better control
- Easy validation
- Predictable behavior
- Dynamic updates
Uncontrolled Components in React
Uncontrolled components use the DOM directly instead of React state.
React uses ref to access input values.
Example of Uncontrolled Component
import { useRef } from "react";
function App() {
const inputRef = useRef();
function handleSubmit() {
alert(inputRef.current.value);
}
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleSubmit}>
Submit
</button>
</div>
);
}
Controlled vs Uncontrolled Components
| Feature | Controlled Component | Uncontrolled Component |
|---|---|---|
| Data Handling | React State | DOM |
| Control | High | Less |
| Validation | Easy | Difficult |
| Recommended | Yes | Limited Use |
Handling Multiple Inputs
Forms often contain multiple fields.
Example
import { useState } from "react";
function App() {
const [formData, setFormData] =
useState({
name: "",
email: ""
});
function handleChange(event) {
setFormData({
...formData,
[event.target.name]:
event.target.value
});
}
return (
<div>
<input type="text" name="name" placeholder="Enter Name" onChange={handleChange} />
<input type="email" name="email" placeholder="Enter Email" onChange={handleChange} />
</div>
);
}
Form Submission in React
React handles form submission using onSubmit.
Example
function App() {
function handleSubmit(event) {
event.preventDefault();
alert("Form Submitted");
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">
Submit
</button>
</form>
);
}
Why preventDefault() is Used?
By default:
- Forms reload the page
preventDefault() stops page refresh.
Form Validation in React
Validation checks whether the user input is correct.
Examples:
- Required fields
- Email validation
- Password length
- Mobile number format
Simple Validation Example
import { useState } from "react";
function App() {
const [email, setEmail] = useState("");
const [error, setError] = useState("");
function handleSubmit(event) {
event.preventDefault();
if (!email.includes("@")) {
setError("Invalid Email");
} else {
setError("");
alert("Success");
}
}
return (
<form onSubmit={handleSubmit}>
<input type="text" onChange={(e) => setEmail(e.target.value) } />
<p>{error}</p>
<button type="submit">
Submit
</button>
</form>
);
}
React Form Events
Common form events:
- onChange
- onSubmit
- onFocus
- onBlur
onFocus Example
<input
type="text"
onFocus={() => alert("Focused")}
/>
onBlur Example
<input
type="text"
onBlur={() => alert("Blur Event")}
/>
Real-Life Example of React Forms
Suppose you are building an e-commerce website.
Forms are used for:
- Login pages
- Signup forms
- Payment details
- Address forms
- Search bars
Without forms, users cannot interact with the website.
Select Dropdown Example
import { useState } from "react";
function App() {
const [city, setCity] = useState("");
return (
<select onChange={(e) => setCity(e.target.value) } >
<option>Delhi</option>
<option>Mumbai</option>
</select>
);
}
Checkbox Example
import { useState } from "react";
function App() {
const [checked, setChecked] = useState(false);
return (
<input type="checkbox" onChange={(e) => setChecked(e.target.checked) } />
);
}
Radio Button Example
<input type="radio" name="gender" value="Male" />
Advantages of React Forms
| Feature | Benefit |
|---|---|
| Dynamic Input Handling | Real-time updates |
| State Management | Better control |
| Validation | Error prevention |
| User Interaction | Better user experience |
| Reusability | Reusable form components |
Common Mistakes in React Forms
1. Forgetting preventDefault()
<form onSubmit={handleSubmit}>
Without preventDefault(), the page reloads.
2. Missing onChange in Controlled Inputs
Wrong:
<input value={name} />
Correct:
<input value={name} onChange={(e) => setName(e.target.value) } />
3. Mutating State Directly
Wrong:
formData.name = "Rahul";
Correct:
setFormData({ ...formData, name: "Rahul" });
4. Using Too Many States
Large forms become difficult to manage with multiple state variables.
5. Not Validating Inputs
Forms without validation may accept invalid data.
Best Practices for React Forms
- Use controlled components
- Validate user input
- Keep form state organized
- Use meaningful input names
- Prevent unnecessary re-renders
- Reuse form components
Real-World Applications of React Forms
React forms are heavily used in:
- Banking apps
- Social media apps
- E-commerce websites
- Admin dashboards
- Booking systems
Examples:
- Login systems
- Registration forms
- Payment forms
- Search functionality
- Contact forms
React Form – Interview Questions
Q 1: What is a form in React?
Q 2: What is a controlled component?
Q 3: How do you handle form submission in React?
Q 4: Why are controlled components preferred?
Q 5: Can multiple inputs be handled with one handler?
Reactjs React Form – Objective Questions (MCQs)
Q1. What is a form in React?
Q2. How do you access form input values in React Functional Components?
Q3. What is a controlled component in React forms?
Q4. How do you handle form submission in React?
Q5. What is the difference between controlled and uncontrolled components in React forms?
Conclusion
React Forms are essential for building interactive web applications because they allow users to enter and submit information dynamically. React provides powerful features such as controlled components, validation, and event handling to manage forms efficiently.