Create a Custom React Hook to Handle Form Fields

Link to chapter - https://serverless-stack.com/chapters/create-a-custom-react-hook-to-handle-form-fields.html

Question-- How would you go about clearing all of the fields in that custom hook? For example, you could have a form where a user could want to submit multiple times; how could you use this hook to easily set each field to an empty string?

That’s a good question. For that I would return another function with the hook that resets the state to the initialState.

I don’t understand the event.target line in the custom React hook:

setValues({
    ...fields,
    [event.target.id]: event.target.value
  });

Why assign event.target.value to event.target.id?

The explanation is:

The only difference here is that we are using event.target.id (which contains the id of our form field) to store the value ( event.target.value ).

I still don’t get it.

Ah, I added a note and edited the chapter. Hope that helps.

In the case of our form the elements, the event.target.id is set as the the controlId. So we are using that as the id in our state.

<FormGroup controlId="email" bsSize="large">
 <ControlLabel>Email</ControlLabel>
 <FormControl
   autoFocus
   type="email"
   value={email}
   onChange={e => setEmail(e.target.value)}
 />
</FormGroup>
1 Like

Got it. So in the state object we end up with a property called “email” that has the value of what the user entered in the form. Thanks!

MS Edge still doesn’t support the es6 spread operator. Therefore this hook will cause the following error: SCRIPT1028 “Expected identifier, string or number”

Whoa that’s weird. Can somebody else confirm this?

How about add react-app-polyfill?