DEV Community

Cover image for Manage Form Input in React with object computed property names
Yuko
Yuko

Posted on

Manage Form Input in React with object computed property names

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);
Enter fullscreen mode Exit fullscreen mode
  1. 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>
      );
Enter fullscreen mode Exit fullscreen mode
  1. 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 });
      };
Enter fullscreen mode Exit fullscreen mode

The whole code is available here

Thank you for reading :)

The original article is here

Top comments (0)