Handling Input Fields in React
Learn how to handle text, email, password, and number inputs in React using state and event handlers.
1. Introduction to Input Fields
Input fields allow users to enter information into a form. Examples include student names, email addresses, passwords, phone numbers, and ages.
In React, input values can be managed using state. The onChange event handler responds when the user changes an input value, and the value prop connects the input to React state.
value,
onChange, and the useState hook.
2. Handling a Text Input
A text input accepts text from the user. We can store the entered text in a state variable and display it on the page.
Example
import { useState } from "react";
function StudentName() {
const [name, setName] = useState("");
function handleChange(event) {
setName(event.target.value);
}
return (
<div>
<label htmlFor="studentName">
Student Name:
</label>
<input
id="studentName"
type="text"
value={name}
onChange={handleChange}
/>
<p>Student Name: {name}</p>
</div>
);
}
export default StudentName;
Expected Output
Student Name: Samadhan Samiksha
When the user types a name, handleChange reads the new value from event.target.value and updates the name state. React then displays the updated name.
3. Handling an Email Input
An email input is used to collect an email address. The type="email" attribute provides browser-level email format checking when the form is submitted.
Example
import { useState } from "react";
function EmailInput() {
const [email, setEmail] = useState("");
return (
<div>
<label htmlFor="email">Email Address:</label>
<input
id="email"
type="email"
value={email}
onChange={(event) =>
setEmail(event.target.value)
}
/>
<p>Email: {email}</p>
</div>
);
}
export default EmailInput;
Expected Output
Email: samadhan@example.com
4. Handling a Password Input
A password input accepts confidential text and hides the characters visually. React can manage its value using state in the same way as other controlled inputs.
Example
import { useState } from "react";
function PasswordInput() {
const [password, setPassword] = useState("");
return (
<div>
<label htmlFor="password">Password:</label>
<input
id="password"
type="password"
value={password}
onChange={(event) =>
setPassword(event.target.value)
}
/>
<p>Password length: {password.length}</p>
</div>
);
}
export default PasswordInput;
Expected Output
Password length: 9
The password input hides the characters on screen. This example displays only the number of characters, not the password itself.
5. Handling a Number Input
A number input allows users to enter numeric values. The input's event.target.value is still returned as a string, so convert it when a numeric value is needed.
Example
import { useState } from "react";
function StudentAge() {
const [age, setAge] = useState("");
function handleChange(event) {
setAge(event.target.value);
}
return (
<div>
<label htmlFor="age">Age:</label>
<input
id="age"
type="number"
value={age}
onChange={handleChange}
/>
<p>Age: {age}</p>
<p>Next Year: {Number(age || 0) + 1}</p>
</div>
);
}
export default StudentAge;
Expected Output
Age: 20
Next Year: 21
The age is stored as the input string. Number() converts it to a number for the calculation. The example uses zero when the field is empty.
6. Handling Multiple Input Fields
A form can contain multiple input fields. We can store their values in a single state object and update the appropriate property using each input's name attribute.
Example: Student Details
import { useState } from "react";
function StudentDetails() {
const [student, setStudent] = useState({
name: "Samadhan Samiksha",
email: "",
age: ""
});
function handleChange(event) {
const { name, value } = event.target;
setStudent((previousStudent) => ({
...previousStudent,
[name]: value
}));
}
return (
<div>
<label htmlFor="name">Name:</label>
<input
id="name"
name="name"
value={student.name}
onChange={handleChange}
/>
<label htmlFor="email">Email:</label>
<input
id="email"
name="email"
type="email"
value={student.email}
onChange={handleChange}
/>
<label htmlFor="age">Age:</label>
<input
id="age"
name="age"
type="number"
value={student.age}
onChange={handleChange}
/>
<p>Name: {student.name}</p>
<p>Email: {student.email}</p>
<p>Age: {student.age}</p>
</div>
);
}
export default StudentDetails;
Expected Output
Name: Samadhan Samiksha
Email: samadhan@example.com
Age: 20
The name attribute identifies the state property to update. The spread operator preserves the other student details when one field changes.
7. Handling Input Changes with Events
The onChange event handler receives an event object. The event.target property refers to the input that triggered the event.
Example
function handleChange(event) {
const inputName = event.target.name;
const inputValue = event.target.value;
console.log(inputName, inputValue);
}
| Property | Purpose |
|---|---|
event.target |
Identifies the input element that triggered the event. |
event.target.value |
Reads the current input value. |
event.target.name |
Identifies the input field by its name attribute. |
event.target.type |
Reads the input element's type. |
8. Common Mistakes
Mistake 1: Forgetting the onChange Handler
<input value={name} />
The input is controlled by the name state, but there is no handler to update that state when the user types.
Correct Code
<input
value={name}
onChange={(event) =>
setName(event.target.value)
}
/>
Mistake 2: Forgetting the name Attribute
<input
value={student.email}
onChange={handleChange}
/>
If a shared handler uses event.target.name to identify the property, the input needs the correct name attribute.
Correct Code
<input
name="email"
value={student.email}
onChange={handleChange}
/>
Mistake 3: Treating Number Input Values as Numbers
const [age, setAge] = useState("");
function handleChange(event) {
setAge(event.target.value);
}
Input values are strings by default, including values read from number inputs. Convert the value when a numeric calculation is required.
Correct Calculation
const nextYear = Number(age || 0) + 1;
9. Practice Tasks
Complete these tasks to practise handling input fields.
Summary
Handling input fields in React involves connecting input values to state and updating them through onChange event handlers. Text, email, password, and number inputs can all be managed as controlled components. Multiple fields can share a state object, with each input's name attribute identifying the property to update. Input values are strings by default, so numeric conversion is required when performing calculations. These techniques provide a foundation for creating student registration and course enquiry forms at CIIT Training Institute.