Handling form inputs in React efficiently often involves using inline onChange
event handlers. This approach helps keep your code concise while maintaining control over input values via component state. In this article, we’ll walk through how to use inline onChange
to update form values in React using the useState
hook.
Step 1: Initialize Form State
Use React's useState
hook to store form data in a single state object:
jsx
const [formData, setFormData] = useState({
name: '',
email: '',
});
This state holds the values for the name
and email
fields.
Step 2: Create an Inline onChange
Handler
Use an inline function in your onChange
prop to update the state when the user types in the input fields. Here’s the full example:
jsx
import React, { useState } from 'react';
const InlineForm = () => {
const [formData, setFormData] = useState({
name: '',
email: '',
});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData((prev) => ({
...prev,
[name]: value,
}));
};
const handleSubmit = (e) => {
e.preventDefault();
console.log('Form data submitted:', formData);
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>Name: </label>
<input
type="text"
name="name"
value={formData.name}
onChange={(e) => handleChange(e)}
/>
</div>
<div>
<label>Email: </label>
<input
type="email"
name="email"
value={formData.email}
onChange={(e) => handleChange(e)}
/>
</div>
<button type="submit">Submit</button>
</form>
);
};
export default InlineForm;
Explanation
- State Setup:
formData
is initialized with name
and email
fields. - handleChange Function:
- Gets the
name
and value
from the input that triggered the change. - Updates the corresponding key in the state using computed property names (
[name]
). - Inline
onChange
: Each <input>
element uses onChange={(e) => handleChange(e)}
. - Form Submission: The form logs the values on submission and prevents the default browser reload.
Benefits of Inline onChange
- Cleaner JSX compared to writing a separate function for each input.
- Easy to scale: Just add new fields to
formData
and match them via the name
attribute. - Great for controlled components: You keep full control of form inputs using React state.
Summary
- Use
useState
to manage form state. - Use a shared
handleChange
method to update state based on name
and value
. - Keep
onChange
inline for readability and simplicity. - Controlled inputs ensure a consistent and predictable UI.