top | item 32919666

(no title)

vcanales | 3 years ago

I know it's not the point, but you can generalize the input handler in the first example by using the name of the input field as a key — in most simple forms, at least:

```

const Form = () => {

  const [formData, setFormData] = useState({ firstName: '', lastName: '' });

  function handleChange(event) {
    const { target } = event;
    const { name, value } = target; // Destructuring in steps to make it easier to figure out where values come from.

    setFormData({
      ...formData,
      [name]: value
    });
  }
  

  return (
    <>
      <input name="firstName" value={formData.firstName} onChange={handleChange} />
      <input name="lastName" value={formData.lastName} onChange={handleChange} />
    </>
  )
}

```

discuss

order

11235813213455|3 years ago

even better, wrap those props as

    <input {...getProps('firstName')} />
and make a custom hook returning that getProps function