Handling Input Fields in React JS
Course: React JS Training
Topic: Handling Input Fields in React
Learning Objectives: Understand how to create input fields, capture user input, manage values using React state, handle different input types, validate form data, manage multiple fields, and build a practical registration form.
1. Introduction to Handling Input Fields
Handling input fields in React means collecting, managing, validating, and processing information entered by users through form elements such as text boxes, email fields, password fields, checkboxes, radio buttons, dropdowns, and textareas.
React provides event handlers such as onChange, onSubmit, and onBlur to respond to user interactions. The useState() Hook is commonly used to store input values and update the user interface when those values change.
React forms generally use two approaches: controlled components and uncontrolled components. In controlled components, React state manages the current value. In uncontrolled components, the browser DOM manages the current value, which can be read through refs or the FormData API.
Example of an Input Field
function NameInput() {
return (
<div>
<label htmlFor="username">Enter Your Name:</label>
<input
type="text"
id="username"
name="username"
placeholder="Enter your name"
/>
</div>
);
}
export default NameInput;
Explanation: The input element creates a text field. The type attribute defines the kind of input, id connects the label to the field, name identifies the form field, and placeholder displays a hint when the field is empty.
2. Types of Input Fields in React
React supports standard HTML input elements. The input type determines what kind of data the user can enter and which browser features are available.
| Input Type |
Purpose |
Example |
text |
Collects general text |
Full name |
email |
Collects an email address |
[email protected] |
password |
Hides typed characters visually |
Account password |
number |
Collects numeric input |
Age or quantity |
tel |
Collects telephone information |
Phone number |
date |
Collects a date |
Date of birth |
checkbox |
Allows a user to select or deselect an option |
Accept terms |
radio |
Allows one selection from a related group |
Study mode |
file |
Allows a user to select files |
Upload a document |
search |
Collects search queries |
Search courses |
range |
Selects a value within a range |
Volume or rating |
Example: Different Input Types
function InputTypes() {
return (
<form>
<label htmlFor="name">Name:</label>
<input id="name" type="text" name="name" />
<label htmlFor="email">Email:</label>
<input id="email" type="email" name="email" />
<label htmlFor="password">Password:</label>
<input id="password" type="password" name="password" />
<label htmlFor="age">Age:</label>
<input id="age" type="number" name="age" />
<button type="submit">Submit</button>
</form>
);
}
export default InputTypes;
3. Understanding Controlled Input Fields
A controlled input is a form element whose current value is controlled by React state. React passes the value to the input using the value prop, and an event handler updates the state when the user types.
For text inputs, a controlled component usually uses value and onChange. For checkboxes and radio buttons, it uses checked and onChange.
Example: Controlled Text Input
import { useState } from "react";
function ControlledInput() {
const [name, setName] = useState("");
function handleChange(event) {
setName(event.target.value);
}
return (
<div>
<label htmlFor="name">Enter Your Name:</label>
<input
id="name"
type="text"
value={name}
onChange={handleChange}
placeholder="Enter your name"
/>
<p>Your Name: {name}</p>
</div>
);
}
export default ControlledInput;
How the Code Works
useState("") initializes the input value as an empty string.
value={name} makes the input display the current state value.
onChange={handleChange} runs when the user edits the input.
event.target.value retrieves the latest text entered by the user.
setName() updates the state, causing React to render the updated value.
{name} displays the current input below the text field.
Important: A controlled text input should receive a string value throughout its lifetime. Use "" for an initially empty field rather than null or undefined.
4. Understanding the onChange Event
The onChange event handler responds to user changes in an input field. It is commonly used to read the new value and update the relevant React state.
Example
import { useState } from "react";
function EmailInput() {
const [email, setEmail] = useState("");
return (
<div>
<input
type="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
placeholder="Enter your email"
/>
<p>Email entered: {email}</p>
</div>
);
}
export default EmailInput;
Whenever the user changes the email field, React receives the new value and updates the state. The paragraph then displays the latest email text.
Common Event Properties
event.target: Refers to the element that triggered the event.
event.target.value: Returns the current value of a text-like input, select, or textarea.
event.target.checked: Returns the checked status of a checkbox or radio button.
event.target.name: Returns the field's name.
event.target.type: Returns the input type.
5. Handling Multiple Input Fields
Forms often contain multiple input fields, such as name, email, phone number, and password. Instead of creating a separate state variable for each field, you can store related values in one state object.
Example: Multiple Inputs with One State Object
import { useState } from "react";
function UserForm() {
const [formData, setFormData] = useState({
name: "",
email: "",
phone: ""
});
function handleChange(event) {
const { name, value } = event.target;
setFormData((previousData) => ({
...previousData,
[name]: value
}));
}
return (
<form>
<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}
/>
<label htmlFor="phone">Phone:</label>
<input
id="phone"
name="phone"
type="tel"
value={formData.phone}
onChange={handleChange}
/>
<p>Name: {formData.name}</p>
<p>Email: {formData.email}</p>
<p>Phone: {formData.phone}</p>
</form>
);
}
export default UserForm;
Explanation
formData stores all three input values in one object.
- Each input has a
name attribute matching a property in the object.
handleChange() identifies which field changed using event.target.name.
event.target.value obtains the new field value.
- The spread operator
... preserves the other existing properties.
- The computed property
[name] updates only the field that changed.
Best Practice: When updating an object in state, create a new object and preserve the previous fields. Do not mutate the existing state object directly.
6. Handling Textarea Fields
A textarea is used to collect longer text, such as comments, descriptions, messages, or feedback. In React, a controlled textarea uses value and onChange.
Example
import { useState } from "react";
function FeedbackForm() {
const [feedback, setFeedback] = useState("");
return (
<div>
<label htmlFor="feedback">Enter Feedback:</label>
<textarea
id="feedback"
value={feedback}
onChange={(event) => setFeedback(event.target.value)}
placeholder="Write your feedback here"
rows={5}
/>
<p>Characters entered: {feedback.length}</p>
</div>
);
}
export default FeedbackForm;
In this example, the textarea's value is stored in React state. The character count updates whenever the user enters or removes text.
7. Handling Select Dropdown Fields
A select element lets users choose an option from a dropdown. In a controlled select, React manages the selected option through the value prop.
Example
import { useState } from "react";
function CourseSelector() {
const [course, setCourse] = useState("");
return (
<div>
<label htmlFor="course">Choose a Course:</label>
<select
id="course"
value={course}
onChange={(event) => setCourse(event.target.value)}
>
<option value="">Select a course</option>
<option value="React JS">React JS</option>
<option value="Flutter">Flutter</option>
<option value="Selenium">Selenium</option>
</select>
<p>Selected Course: {course || "None"}</p>
</div>
);
}
export default CourseSelector;
The selected option is stored in the course state variable. When the user chooses a different course, the change handler updates that state.
8. Handling Checkbox Fields
A checkbox is used when users can select or deselect an option, such as agreeing to terms or enabling notifications. For a controlled checkbox, use the checked prop rather than value to control whether it is selected.
Example
import { useState } from "react";
function TermsCheckbox() {
const [accepted, setAccepted] = useState(false);
return (
<div>
<label>
<input
type="checkbox"
checked={accepted}
onChange={(event) => setAccepted(event.target.checked)}
/>
I accept the terms and conditions
</label>
<p>Status: {accepted ? "Accepted" : "Not accepted"}</p>
</div>
);
}
export default TermsCheckbox;
Important: For checkboxes, use event.target.checked to read the selected status. The result is a Boolean value: true or false.
9. Handling Radio Button Fields
Radio buttons allow users to select one option from a group. Radio buttons that belong to the same group should share the same name.
Example
import { useState } from "react";
function StudyMode() {
const [mode, setMode] = useState("");
return (
<div>
<p>Choose Study Mode:</p>
<label>
<input
type="radio"
name="studyMode"
value="Online"
checked={mode === "Online"}
onChange={(event) => setMode(event.target.value)}
/>
Online
</label>
<label>
<input
type="radio"
name="studyMode"
value="Classroom"
checked={mode === "Classroom"}
onChange={(event) => setMode(event.target.value)}
/>
Classroom
</label>
<p>Selected Mode: {mode || "Not selected"}</p>
</div>
);
}
export default StudyMode;
The mode state stores the selected option. Each radio button's checked prop determines whether its value matches the current state.
10. Handling Number Input Fields
An input with type="number" is useful for quantities, ages, prices, and other numeric values. However, the DOM's event.target.value is still a string, so conversion may be necessary when performing calculations.
Example
import { useState } from "react";
function AgeInput() {
const [age, setAge] = useState("");
const numericAge = age === "" ? null : Number(age);
return (
<div>
<label htmlFor="age">Enter Your Age:</label>
<input
id="age"
type="number"
min="1"
max="120"
value={age}
onChange={(event) => setAge(event.target.value)}
/>
<p>
{numericAge === null
? "Enter your age"
: `Your age is ${numericAge}`}
</p>
</div>
);
}
export default AgeInput;
Keeping the input state as a string allows the field to represent an empty value. Convert it to a number when numeric operations are needed, and validate the result before using it.
11. Handling Input Fields with a Reusable Change Handler
When several controlled fields share one state object, a reusable change handler reduces repeated code. The input's name determines which state property is updated.
Example
import { useState } from "react";
function LoginForm() {
const [form, setForm] = useState({
username: "",
password: ""
});
function handleChange(event) {
const { name, value } = event.target;
setForm((previousForm) => ({
...previousForm,
[name]: value
}));
}
return (
<form>
<input
name="username"
value={form.username}
onChange={handleChange}
placeholder="Username"
/>
<input
name="password"
type="password"
value={form.password}
onChange={handleChange}
placeholder="Password"
/>
</form>
);
}
export default LoginForm;
Both fields use the same handler, but each updates a different property because their name attributes differ.
12. Handling Form Submission
Form submission is the process of collecting the entered information and processing it. React commonly handles submission through the form's onSubmit event.
Example
import { useState } from "react";
function SimpleForm() {
const [name, setName] = useState("");
function handleSubmit(event) {
event.preventDefault();
const cleanedName = name.trim();
if (!cleanedName) {
alert("Please enter your name.");
return;
}
alert(`Welcome, ${cleanedName}!`);
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="name">Name:</label>
<input
id="name"
value={name}
onChange={(event) => setName(event.target.value)}
required
/>
<button type="submit">Submit</button>
</form>
);
}
export default SimpleForm;
Key Concepts
onSubmit runs when the form is submitted.
event.preventDefault() prevents the browser's default page navigation or reload.
trim() removes leading and trailing whitespace from the name.
- The handler checks whether the cleaned value is empty before processing it.
type="submit" explicitly marks the button as the form submission button.
13. Input Validation in React
Input validation checks whether the entered information meets the application's requirements. Validation helps prevent incomplete or incorrectly formatted information from being processed.
Common Validation Rules
- Name should not be empty or consist only of whitespace.
- Email should have a valid email format.
- Password should meet the application's length and complexity requirements.
- Phone number should follow the expected format.
- Required dropdown fields should have a selected option.
- Checkboxes may need to be selected before submission.
- Numeric fields should fall within the allowed range.
Example: Basic Name Validation
import { useState } from "react";
function NameValidation() {
const [name, setName] = useState("");
const [error, setError] = useState("");
function handleChange(event) {
setName(event.target.value);
if (event.target.value.trim()) {
setError("");
}
}
function handleSubmit(event) {
event.preventDefault();
if (!name.trim()) {
setError("Name is required.");
return;
}
setError("");
alert("Form submitted successfully!");
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="name">Name:</label>
<input
id="name"
value={name}
onChange={handleChange}
aria-invalid={Boolean(error)}
aria-describedby={error ? "name-error" : undefined}
/>
{error && (
<p id="name-error" role="alert">{error}</p>
)}
<button type="submit">Submit</button>
</form>
);
}
export default NameValidation;
Explanation: The example stores the input and error message in state. It displays an error when the user submits an empty name and clears the error when the user enters a non-whitespace value.
Security note: Client-side validation improves the user experience but can be bypassed. Validate important data on the server as well.
14. Resetting Input Fields
Resetting a form clears its fields or returns them to their initial values. In a controlled form, update the state variables to their initial values. In an uncontrolled form, a form element's native reset() method can restore its default values.
Example: Reset a Controlled Input
import { useState } from "react";
function ResetForm() {
const [name, setName] = useState("");
function handleReset() {
setName("");
}
return (
<div>
<input
value={name}
onChange={(event) => setName(event.target.value)}
placeholder="Enter name"
/>
<button type="button" onClick={handleReset}>
Clear
</button>
</div>
);
}
export default ResetForm;
Here, clicking Clear sets the state back to an empty string, so the input displays no text.
15. Complete Practical Project: Student Registration Form
This project combines input handling, controlled components, multiple fields, dropdown selection, checkbox management, validation, and form submission.
Project Features
- Collects the student's name, email, phone number, and course.
- Uses controlled input fields with React state.
- Uses a reusable change handler for text-based fields.
- Uses a controlled select dropdown and checkbox.
- Validates required fields and basic input requirements.
- Displays the submitted registration details.
- Provides a reset button to clear the form.
Complete Code
import { useState } from "react";
function StudentRegistrationForm() {
const initialForm = {
name: "",
email: "",
phone: "",
course: ""
};
const [formData, setFormData] = useState(initialForm);
const [acceptedTerms, setAcceptedTerms] = useState(false);
const [submittedStudent, setSubmittedStudent] = useState(null);
const [error, setError] = useState("");
function handleChange(event) {
const { name, value } = event.target;
setFormData((previousData) => ({
...previousData,
[name]: value
}));
}
function handleSubmit(event) {
event.preventDefault();
const name = formData.name.trim();
const email = formData.email.trim();
const phone = formData.phone.trim();
if (!name || !email || !phone || !formData.course) {
setError("Please complete all required fields.");
return;
}
if (!acceptedTerms) {
setError("Please accept the terms and conditions.");
return;
}
setError("");
setSubmittedStudent({
name,
email,
phone,
course: formData.course
});
}
function handleReset() {
setFormData(initialForm);
setAcceptedTerms(false);
setSubmittedStudent(null);
setError("");
}
return (
<div>
<h2>Student Registration Form</h2>
<form onSubmit={handleSubmit} onReset={handleReset}>
<label htmlFor="studentName">Student Name:</label>
<input
id="studentName"
name="name"
value={formData.name}
onChange={handleChange}
placeholder="Enter your name"
required
/>
<label htmlFor="studentEmail">Email:</label>
<input
id="studentEmail"
name="email"
type="email"
value={formData.email}
onChange={handleChange}
placeholder="Enter your email"
required
/>
<label htmlFor="studentPhone">Phone Number:</label>
<input
id="studentPhone"
name="phone"
type="tel"
value={formData.phone}
onChange={handleChange}
placeholder="Enter your phone number"
required
/>
<label htmlFor="course">Select Course:</label>
<select
id="course"
name="course"
value={formData.course}
onChange={handleChange}
required
>
<option value="">Choose a course</option>
<option value="React JS">React JS</option>
<option value="Flutter">Flutter</option>
<option value="Selenium">Selenium</option>
</select>
<label>
<input
type="checkbox"
checked={acceptedTerms}
onChange={(event) => setAcceptedTerms(event.target.checked)}
/>
I accept the terms and conditions
</label>
{error && <p role="alert">{error}</p>}
<button type="submit">Register</button>
<button type="reset">Reset Form</button>
</form>
{submittedStudent && (
<section>
<h3>Registration Successful</h3>
<p>Name: {submittedStudent.name}</p>
<p>Email: {submittedStudent.email}</p>
<p>Phone: {submittedStudent.phone}</p>
<p>Course: {submittedStudent.course}</p>
</section>
)}
</div>
);
}
export default StudentRegistrationForm;
Project Explanation
- Initial state: The
initialForm object defines empty values for the four form fields.
- State management:
useState() stores the field values, terms acceptance, validation error, and submitted student information.
- Reusable handler:
handleChange() updates the field identified by the input's name.
- Checkbox handling: The checkbox uses
checked and reads its new status from event.target.checked.
- Form submission:
handleSubmit() prevents normal browser submission and checks the required information.
- Result display: After successful validation, the submitted information appears below the form.
- Reset: The reset handler restores all state values and clears the error and result.
Production improvement: This example demonstrates client-side form handling. A real registration application should also validate data on the server, handle API errors, and use secure storage and transport for personal information.
16. Controlled vs Uncontrolled Input Fields
Understanding the difference between controlled and uncontrolled input fields helps you choose the correct approach for each form.
| Feature |
Controlled Input |
Uncontrolled Input |
| Value management |
Managed by React state |
Managed by the DOM |
| Common properties |
value or checked |
defaultValue or defaultChecked |
| Change handling |
Usually updates state through onChange |
No change handler is needed just to maintain the value |
| Reading the value |
Read from state |
Read using a ref or FormData |
| Live validation |
Easy to implement |
Requires additional event handling or submit-time validation |
| Dynamic interface updates |
Convenient |
Requires additional logic if the UI depends on input changes |
| Common use cases |
Search, filters, dependent fields, live feedback |
Simple forms and submit-time collection |
17. Common Mistakes When Handling Input Fields
Mistake 1: Forgetting the onChange Handler
// Incorrect for an editable controlled input:
<input value={name} />
// Correct:
<input
value={name}
onChange={(event) => setName(event.target.value)}
/>
If you pass a fixed or state-based value without updating it through an appropriate handler, React will keep displaying that value and the input may appear read-only.
Mistake 2: Using value Instead of checked for a Checkbox
// Correct checkbox control:
<input
type="checkbox"
checked={accepted}
onChange={(event) => setAccepted(event.target.checked)}
/>
Use checked to control selection status and event.target.checked to read the new Boolean value.
Mistake 3: Mutating State Directly
// Incorrect:
formData.name = "Rahul";
// Correct:
setFormData((previousData) => ({
...previousData,
name: "Rahul"
}));
React state should be updated immutably so React can correctly identify and render the updated data.
Mistake 4: Losing Other Properties in an Object
// Incorrect: replaces the entire object with one property.
setFormData({ name: event.target.value });
// Correct: preserves other properties.
setFormData((previousData) => ({
...previousData,
name: event.target.value
}));
Mistake 5: Initializing a Controlled Input with undefined
// Prefer:
const [name, setName] = useState("");
// Avoid allowing a controlled value to switch between
// undefined and a string.
Keep controlled text values as strings throughout the component's lifetime. For checkboxes, keep the controlled checked value Boolean.
Mistake 6: Forgetting event.preventDefault()
When processing a form through a custom onSubmit handler without a page reload, call event.preventDefault(). Otherwise, the browser may submit the form normally and navigate or refresh.
Mistake 7: Using the Wrong Event Value
Use event.target.value for text-like fields and dropdowns, but use event.target.checked for checkbox selection. Convert numeric text to a number when calculations require it.
18. Best Practices for Handling Input Fields
- Use controlled inputs when React needs to respond immediately to changes.
- Use meaningful variable names that describe each field's purpose.
- Use
label elements connected with htmlFor and matching input id values.
- Use the correct input type, such as
email, password, number, or date.
- Use a reusable change handler for forms with several related fields.
- Use the spread operator when updating an object in state.
- Use
required, min, max, and other suitable HTML validation attributes.
- Show helpful validation messages and associate them with their inputs when appropriate.
- Keep controlled values initialized to suitable types.
- Use
type="button" for buttons that should not submit a form, and type="submit" for the submit button.
- Validate important data on the server, not only in the browser.
- Keep input state close to the component that needs it to avoid unnecessary re-renders.
- Never expose passwords or other sensitive input values in logs or on the screen unnecessarily.
19. Practical Use Cases of Input Fields
- Login form: Collect username or email and password.
- Registration form: Collect personal and course information.
- Search bar: Filter products, courses, or records based on text.
- Contact form: Collect a name, email, subject, and message.
- Feedback form: Collect ratings, comments, and suggestions.
- Booking form: Collect dates, times, and the number of participants.
- Settings page: Allow users to update preferences.
- Admin dashboard: Collect data for creating or editing records.
20. Interview Questions and Answers
Q1. What does handling input fields mean in React?
Answer: It means collecting and managing user-entered information using input elements, event handlers, state, refs, and form submission logic.
Q2. What is a controlled input?
Answer: A controlled input is a form element whose current value is managed by React state through props such as value or checked.
Q3. What is the purpose of onChange?
Answer: The onChange handler responds to user changes and is commonly used to update React state with the latest input value.
Q4. What does event.target.value return?
Answer: It returns the current value of the input element that triggered the event, usually as a string.
Q5. How do you handle multiple input fields with one function?
Answer: Give each field a name attribute, read event.target.name and event.target.value, and use a computed property with the spread operator to update the matching state property.
Q6. How do you handle checkboxes in React?
Answer: For controlled checkboxes, use the checked prop and update state from event.target.checked.
Q7. How do you handle dropdowns?
Answer: A controlled dropdown uses value and onChange to store the selected option in React state.
Q8. Why do we use event.preventDefault()?
Answer: It prevents the browser's default form submission behavior, allowing React to process the submitted values without the usual navigation or reload.
Q9. What is the difference between value and defaultValue?
Answer: value controls the current input value through React, while defaultValue specifies the initial value for an uncontrolled input.
Q10. How can you validate input fields?
Answer: You can combine HTML attributes such as required and type="email" with custom JavaScript validation and server-side validation.
Q11. How do you reset controlled fields?
Answer: Update their React state to the initial values. The input elements then display those values automatically.
Q12. Why should state objects be updated immutably?
Answer: Creating a new object preserves the previous state and allows React to detect updates correctly without directly mutating the existing object.
21. Practice Exercises
- Create a text input that displays the user's name as they type.
- Create a controlled email field with basic validation.
- Build a password field and add a button to show or hide the password.
- Create a number input that calculates the square of the entered number.
- Build a dropdown that allows users to choose a React, Flutter, or Selenium course.
- Create a checkbox that enables or disables a Submit button.
- Build a radio-button group for selecting online or classroom training.
- Create a textarea that displays a live character count.
- Build a contact form using a single state object and reusable change handler.
- Create a registration form with validation, submission, and reset functionality.
22. Quick Revision
- Input fields collect information from users.
useState() stores and updates controlled input values.
value controls text-like input values.
checked controls checkbox and radio selection.
onChange responds to user edits.
event.target.value reads a field's current value.
event.target.checked reads a checkbox's selected state.
event.target.name identifies a field for reusable handlers.
event.preventDefault() prevents the browser's default form submission behavior.
- Validation checks whether the entered information meets requirements.
- Resetting controlled inputs requires resetting the corresponding state.
- Server-side validation is important for real applications.
23. Official React Documentation
24. React JS Training at JustAcademy
Learn React JS concepts such as components, JSX, props, state, event handling, form controls, validation, and practical application development through structured training.
JustAcademy React JS Training
To explore a course demo, register using the following link.
Register for React JS Course Demo
Conclusion
Handling input fields is an essential part of React development because forms allow users to provide information and interact with applications. By understanding input types, the onChange event, React state, reusable handlers, validation, and form submission, you can build reliable and user-friendly forms. Practise these techniques by creating login forms, contact forms, search bars, and student registration projects.