DEV Community

Discussion on: How to handle inputs with React

Collapse
 
briang123 profile image
Brian Gaines • Edited

Keep up the work! You may want to consider revising your onChange event to eliminate those switch case statements by structuring your input onChange event handler to point to a function that takes in the event target. This will allow your onChange to be more generic. I've also included an updateState function, as well here. As far as your setState, you might be able to improve that by using destructuring.

updateState = (key, value) => this.setState((prevState, props) => (prevState[key] = value));

onChange = e => this.updateState([e.target.name], e.target.value);

input type="text" name="mycontrol" value={this.state.mycontrol} onChange={this.onChange}

Collapse
 
jakesweb profile image
Jacob Colborn

Good tips. I am going to look into those. I was trying to think of a way to make the onChange more generic but could not come up with anything. Your way is very clear.