If your form has multiple input tags, then it is possible to handle all of them using a single method.
- You have a form containing multiple inputs.
- All those inputs need to be stored in the state.
- You don't want to write a function to handle each of the inputs.
- You want to write only 1 function which can get the input data and store the values in React state.
I will be using react useState hook for using React state. Click here to learn React hooks
The important change is to make use of the name property in the input tag
import React, { useState } from 'react';
// create a global variable to be used as initial value for inputVal state
const userDetails = {
firstName: '',
lastName: '',
email: ''
}
// using a function component with useState hook
const CustomForm = () => {
const [inputVal, setUserDetails] = useState(userDetails);
// function which handles all input changes
const handleChange = (event) => {
setUserDetails({
...inputVal,
[event.target.name]: event.target.value
})
}
return (
<div>
<form>
<label htmlFor='firstName'>First Name: </label>
<input
label='First Name'
id='firstName'
name='firstName'
value={inputVal.firstName}
onChange={handleChange} /><br />
<label htmlFor='lastName'>Last Name: </label>
<input
label='Last Name'
id='lastName'
name='lastName'
value={inputVal.lastName}
onChange={handleChange} /><br />
<label htmlFor='email'>Email: </label>
<input
label='Email'
id='email'
name='email'
value={inputVal.email}
onChange={handleChange} /><br />
</form>
<hr />
{/* display the input values stored in the state */}
<div>
<h1>First name is: {inputVal.firstName}</h1>
<h1>Last name is: {inputVal.lastName}</h1>
<h1>Email is: {inputVal.email}</h1>
</div>
</div>
);
}
export default CustomForm;
#reactjs #shorts