DEV Community

Discussion on: Creating a custom hook in React to control form input

Collapse
leob profile image
leob • Edited on

Well it's not just you, I also fail to grasp how this works. The idea seems nice, but the author could have elaborated just a tiny little bit more for the mere mortals among us.

Ah on reading it a second time I get it now ... for a second field (let's say "email") you'd just do:

const {reset, ...email} = useField('text')
Enter fullscreen mode Exit fullscreen mode

so for those 2 fields you'd have (we need to "rename" the 'reset' member during destructuring):

const {reset: resetUsername, ...username} = useField('text')
const {reset: resetEmail, ...email} = useField('text')
...
<input {...username} type='text' id='username'/>
<input {...email} type='text' id='email'/>
Enter fullscreen mode Exit fullscreen mode

and so on ... the only thing I don't get is why we need the "type" parameter to the hook: useField('text') ... and we probably also don't need the "id" attributes (id='username' and id='email').

So, this might work equally well (and save some typing) ... ?

const {reset: resetUsername, ...username} = useField()
const {reset: resetEmail, ...email} = useField()
...
<input {...username} type='text'/>
<input {...email} type='text'/>
Enter fullscreen mode Exit fullscreen mode

Other than that, yeah pretty clever and elegant.

Collapse
webzth profile image
WebDevZTH Author

Yeah absolutely, we need not have multiple onChange handlers either. The type parameter is for the input element's type attribute is required to mention what type of input it is, could be email, password, text, number, range etc.

Collapse
leandroreschke profile image
Leandro Reschke • Edited on

I came to the same conclusion, but if this is true, then now I have multiple useFields instead of useStates, it is just omitting value and onChange. About the Type parameter, I think he wanted to also set the input type.

Thread Thread
leob profile image
leob

Yes you'd have multiple useFields, I think that's clearly the idea.

But it's not omitting value and onChange - instead, value and onChange are being expanded as props on the elements, so you're effectively linking the attributes on the input elements with function closures which are generated by the "useField" calls.

I still don't see the point of the type param, unless you'd end up with just:

<input {...email}/>
Enter fullscreen mode Exit fullscreen mode

where the 'type' attribute is then also generated through the object expansion (the ... ellipsis).