This is my memo for form input management with computed property names.
- set form Input state
const initFormInput = {
firstName: "",
lastName: "",
email: ""
};
const [formInput, setFormInput] = useState(initFormInput);
- write JSX
return (
<FormContainer onSubmit={submitHandler}>
<label>First Name</label>
<Input
type="text"
required
onChange={changeHandler}
name="firstName"
value={firstName}
/>
<label>Last Name</label>
<Input
type="text"
required
onChange={changeHandler}
name="lastName"
value={lastName}
/>
<label>Email</label>
<Input
type="email"
required
onChange={changeHandler}
name="email"
value={email}
/>
<button type="submit">Submit</button>
</FormContainer>
);
- define changeHandler
You can dynamically access appropriate property name of formInput object by using [].
const changeHandler = (event) => {
const { name, value } = event.target;
setFormInput({ ...formInput, [name]: value });
};
The whole code is available here
Thank you for reading :)
The original article is here
Top comments (0)