Manage Form Input in React with object computed property names

Lada496
May 24, 2022

--

This is my memo for form input management with computed property names.

  1. set form Input state
const initFormInput = {
firstName: "",
lastName: "",
email: ""
};
const [formInput, setFormInput] = useState(initFormInput);

2. 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>
);

3. 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 :)

--

--