DEV Community

Discussion on: No need to write change handlers for multiple React inputs!

Collapse
 
andomain profile image
Sam Anderson • Edited

I often further simplify this by giving the <input> elements a name property & then using the following

const changeHandler = (e) => {
   const {name, value} = e.currentTarget;
   setState({[name]: value});
}

...
<input name="name" onChange={changeHandler} />
<input name="age" onChange={changeHandler} />
...

Collapse
 
karataev profile image
Eugene Karataev

For the cases when you don't need current input state for validation, calculation, e.t.c you just can use uncontrolled inputs and read inputs' values via ref.

Collapse
 
nas5w profile image
Nick Scialli (he/him)

Awesome! I do think this will end up with type errors for varied types of object properties (e.g., numbers and booleans)

Collapse
 
andomain profile image
Sam Anderson

Of course, this was just a minimal example. When I use this properly in my Typescript projects I include typeguards etc. to ensure state types remain consistent.