React Forms & Handling User Input
React Forms & Handling User Input
Forms are an essential part of any web application, allowing users to input and submit data. In React, forms are handled differently than in traditional HTML because React uses state and event handlers to control form behavior dynamically. Understanding how to manage forms properly ensures a smooth user experience and enhances application performance.
What Are Controlled Components?
A controlled component is a form element where React controls its value using state.
👉 Example: Controlled Input Field
import React, { useState } from “react”;
function ControlledForm() {
const [name, setName] = useState(“”);
const handleChange = (event) => {
setName(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
alert(`Submitted Name: ${name}`);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type=”text” value={name} onChange={handleChange} />
</label>
<button type=”submit”>Submit</button>
</form>
);
}
export default ControlledForm;
📝 How It Works:
✔️ The input value is stored in state (name).
✔️ The onChange event updates state whenever the user types.
✔️ The onSubmit event prevents page reload and processes the input.
Handling Multiple Input Fields
When handling multiple inputs, using an object for state simplifies the code.
👉 Example: Handling Multiple Fields
import React, { useState } from “react”;
function MultiInputForm() {
const [formData, setFormData] = useState({ name: “”, email: “” });
const handleChange = (event) => {
const { name, value } = event.target;
setFormData((prevData) => ({ …prevData, [name]: value }));
};
const handleSubmit = (event) => {
event.preventDefault();
alert(`Name: ${formData.name}, Email: ${formData.email}`);
};
return (
<form onSubmit={handleSubmit}>
<input
type=”text”
name=”name”
value={formData.name}
onChange={handleChange}
placeholder=”Name”
/>
<input
type=”email”
name=”email”
value={formData.email}
onChange={handleChange}
placeholder=”Email”
/>
<button type=”submit”>Submit</button>
</form>
);
}
export default MultiInputForm;
📝 Explanation
✔️ useState({ name: “”, email: “” }) → Stores multiple input values in one state object.
✔️ handleChange → Updates the respective field dynamically.
✔️ handleSubmit → Prevents default form submission & displays an alert with entered data.
📌 Advantages of Using an Object for State:
✅ Makes managing multiple fields more organized.
✅ Reduces redundant useState calls.
What Are Uncontrolled Components?
Example: Uncontrolled Component
import React, { useRef } from “react”;
function UncontrolledForm() {
const inputRef = useRef();
const handleSubmit = (event) => {
event.preventDefault();
alert(`Entered Value: ${inputRef.current.value}`);
};
return (
<form onSubmit={handleSubmit}>
<input type=”text” ref={inputRef} placeholder=”Enter text” />
<button type=”submit”>Submit</button>
</form>
);
}
export default UncontrolledForm;
📝 Explanation
✔️ Uncontrolled Component → Uses useRef instead of state to handle input.
✔️ useRef() → Directly accesses the DOM element without re-rendering.
✔️ inputRef.current.value → Retrieves input value on form submission.
📌 When to Use Uncontrolled Components?
✅ When integrating with non-React applications.
✅ When managing input values without frequent re-renders.
Handling Different Input Types
React provides ways to handle checkboxes, radio buttons, and dropdowns.
👉 Checkbox Example:
import React, { useState } from “react”;
function CheckboxForm() {
const [isChecked, setIsChecked] = useState(false);
return (
<label>
<input
type=”checkbox”
checked={isChecked}
onChange={() => setIsChecked(!isChecked)}
/>
Accept Terms & Conditions
</label>
);
}
export default CheckboxForm;
📝 Explanation
✔️ useState(false) → Manages the checkbox state.
✔️ checked={isChecked} → Binds the checkbox to state.
✔️ onChange={() => setIsChecked(!isChecked)} → Toggles state when clicked.
👉 Radio Button Example:
import React, { useState } from “react”;
function RadioForm() {
const [gender, setGender] = useState(“male”);
return (
<form>
<label>
<input
type=”radio”
name=”gender”
value=”male”
checked={gender === “male”}
onChange={() => setGender(“male”)}
/>
Male
</label>
<label>
<input
type=”radio”
name=”gender”
value=”female”
checked={gender === “female”}
onChange={() => setGender(“female”)}
/>
Female
</label>
</form>
);
}
export default RadioForm;
📝 Explanation
✔️ useState(“male”) → Manages the selected radio button state.
✔️ checked={gender === “male”} → Ensures the selected option is checked.
✔️ onChange={() => setGender(“male”)} → Updates state when clicked.
👉 Dropdown Example:
return (
<div>
<select value={color} onChange={(e) => setColor(e.target.value)}>
<option value=”red”>Red</option>
<option value=”blue”>Blue</option>
<option value=”green”>Green</option>
</select>
<p>Selected Color: {color}</p>
</div>
);
}
export default SelectForm;
📝 Explanation
✔️ useState(“red”) → Initializes the selected color as “red”.
✔️ value={color} → Binds the dropdown to the state.
✔️ onChange={(e) => setColor(e.target.value)} → Updates state on selection.
Preventing Default Form Submission
React forms do not automatically refresh the page. Use event.preventDefault() to prevent unwanted behavior.
import React, { useState } from “react”;
function SimpleForm() {
const [name, setName] = useState(“”);
const handleSubmit = (event) => {
event.preventDefault(); // Prevents page refresh
console.log(“Form submitted successfully! Name:”, name);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input
type=”text”
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<button type=”submit”>Submit</button>
</form>
);
}
export default SimpleForm;
📝 Explanation
✔️ useState(“”) → Stores the input value.
✔️ event.preventDefault() → Prevents page refresh on form submission.
✔️ console.log(“Form submitted successfully!”) → Displays a message in the console.
Best Practices for Handling Forms in React
✅ Use controlled components for better React state management.
✅ Use refs only when needed to avoid unnecessary re-renders.
✅ Keep form state organized using an object.
✅ Always prevent default submission to avoid page reloads.
✅ Use error handling and validation before submitting data.
Conclusion
Understanding how to handle forms properly in React allows developers to build interactive applications with seamless user input handling. Whether using controlled or uncontrolled components, choosing the right method ensures better performance and maintainability!