Skip to content

Instantly share code, notes, and snippets.

@EnriqueVidal
Last active October 26, 2017 03:26
Show Gist options
  • Save EnriqueVidal/dd2e4e12d63b9e0663fe87784b3e4e5d to your computer and use it in GitHub Desktop.
Save EnriqueVidal/dd2e4e12d63b9e0663fe87784b3e4e5d to your computer and use it in GitHub Desktop.
Pass setState functions instead of objects.
import React from 'react';
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
thingOne: null,
thingTwo: null,
}
}
handleChange = ({ target }) => {
const key = target.name;
const value = target.value;
this.setState(() => ({ [key]: value }));
}
render() {
return (
<form>
<input name="thingOne" onChange={this.handleChange} value={this.state.thingOne} />
<input name="thingTwo" onChange={this.handleChange} value={this.state.thingTwo} />
</form>
);
}
}
@EnriqueVidal
Copy link
Author

With babel-plugin-transform-class-properties you can take advantage of => to bind this for you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment