Forms in React
React forms are commonly used for login pages, registration forms, search fields, and complex multi-step user inputs. By using reusable components, developers can encapsulate form logic, minimize prop drilling, and prevent unnecessary re-renders, which are common performance pitfalls in large applications. Understanding React forms also involves mastering core concepts such as controlled components, state updates, event handling, and lifecycle hooks like useEffect for side effects.
Basic Example
jsximport React, { useState } from 'react';
function SimpleForm() {
const [formData, setFormData] = useState({ name: '', email: '' });
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
};
const handleSubmit = (e) => {
e.preventDefault();
console.log('Submitted Data:', formData);
};
return ( <form onSubmit={handleSubmit}> <div> <label>Name:</label> <input
type="text"
name="name"
value={formData.name}
onChange={handleChange}
/> </div> <div> <label>Email:</label> <input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
/> </div> <button type="submit">Submit</button> </form>
);
}
export default SimpleForm;
In the basic example above, we demonstrate a controlled React form. The useState hook initializes formData with two fields: name and email. The handleChange function dynamically updates the corresponding field in the state using the spread operator, maintaining immutability, which is crucial for React’s rendering optimization. The handleSubmit function prevents the default form submission, allowing custom logic to handle the data, in this case logging it to the console.
Practical Example
jsximport React, { useState, useEffect } from 'react';
function AdvancedForm() {
const [formData, setFormData] = useState({ username: '', password: '' });
const [errors, setErrors] = useState({});
const [isSubmitting, setIsSubmitting] = useState(false);
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
};
const validate = () => {
};
const handleSubmit = (e) => {
e.preventDefault();
setIsSubmitting(true);
setTimeout(() => {
console.log('Form Submitted Successfully:', formData);
setIsSubmitting(false);
}, 1000);
}
};
useEffect(() => {
if (isSubmitting) console.log('Submitting...');
}, [isSubmitting]);
return ( <form onSubmit={handleSubmit}> <div> <label>Username:</label> <input
type="text"
name="username"
value={formData.username}
onChange={handleChange}
/>
{errors.username && <span>{errors.username}</span>} </div> <div> <label>Password:</label> <input
type="password"
name="password"
value={formData.password}
onChange={handleChange}
/>
{errors.password && <span>{errors.password}</span>} </div> <button type="submit" disabled={isSubmitting}>
{isSubmitting ? 'Submitting...' : 'Submit'} </button> </form>
);
}
export default AdvancedForm;
📊 Reference Table
React Element/Concept | Description | Usage Example |
---|---|---|
useState | Manage internal component state | const [value, setValue] = useState(initialValue); |
useEffect | Handle side effects and lifecycle | useEffect(() => { console.log('Mounted'); }, []); |
onChange | Listen for input changes | <input onChange={handleChange} /> |
onSubmit | Handle form submission | <form onSubmit={handleSubmit}></form> |
🧠 Test Your Knowledge
Test Your Knowledge
Challenge yourself with this interactive quiz and see how well you understand the topic
📝 Instructions
- Read each question carefully
- Select the best answer for each question
- You can retake the quiz as many times as you want
- Your progress will be shown at the top