Multiple Controlled Inputs with Single onChange Function in React.js
When building forms in React.js, it’s common to have multiple inputs that need to be controlled, such as text fields, checkboxes, and radio buttons. Handling the onChange event for each input individually can lead to repetitive code, which can be easily avoided by using a single onChange function for all the inputs.
Let’s see how we can achieve this in a simple React.js application:
“`jsx
import React, { useState } from ‘react’;
function App() {
const [formData, setFormData] = useState({
name: ”,
email: ”,
password: ”
});
const handleInputChange = (e) => {
const { name, value } = e.target;
setFormData({ …formData, [name]: value });
};
return (
);
}
export default App;
“`
In this example, we have a form with three input fields: name, email, and password. We’re using the useState hook to create a formData state variable to store the values of the input fields. We also have a handleInputChange function that updates the formData state whenever an input value changes.
By using the spread operator (…) in the setFormData function, we’re able to update the specific input field value without affecting the others. This allows us to have a single onChange function for all the input fields while maintaining individual control over each input.
Overall, using a single onChange function for multiple controlled inputs in React.js can help reduce repetitive code and make the codebase more maintainable. It’s a simple and effective way to handle form inputs in a React.js application.
Makes sense and straight to the point. Liked. Keep it up 👍
Bro I have a doubt , will it render each time when we type a letter in any input field.
easy to use. reasons explained well. other creators be using custom syntax without explaining reason behind logic. great job
Thank you