2 ms·
Another basic ES6 trick that beginners usually don't know: handleChange = event => { this.setState({ [event.currentTarget.name]: event.currentTarget.valu
by ggregoire 8y ago
Another basic ES6 trick that beginners usually don't know:
handleChange = event => {
this.setState({ [event.currentTarget.name]: event.currentTarget.value })
}
So you can handle 10 inputs with the same handler.
- spiritcat 8y agojust blue my mind
- coltonv 8y agoThis is great, and a strategy I used a lot in my last code base. If you do this for statically typed JS though, you'll get either error messages or bad typing with lots of `any`s and weak type checks. Here's a great strategy to do the same thing with strong static types, like in flow and typescript: setTextField = (name: 'name' | 'email' | 'phone') => (event: InputEvent) => { this.setState({ user: { ...this.state.user, [name]: event.target.value } }); } setBooleanField = (name: 'isCool') => (event: InputEvent) => { this.setState({ user: { ...this.state.user, [name]: event.target.checked } }); } render() { <div> <input type="text" onChange={ this.setTextField('email')} placeholder="Email" value={this.state.user.email} /> <input type="checkbox" onChange={ this.setBooleanField('isCool')} checked={this.state.user.isCool} /> </div> } More verbose than the non-typed version, but simpler than declaring a function for every field with all the goodness of strong static typing.