Skip to content

Instantly share code, notes, and snippets.

@etoxin
Created July 18, 2016 03:57
Show Gist options
  • Save etoxin/2e4dd833ba2606c941b9d7fb415f396e to your computer and use it in GitHub Desktop.
Save etoxin/2e4dd833ba2606c941b9d7fb415f396e to your computer and use it in GitHub Desktop.
Improved example of React data-binding
/*
* Improving upon example at: http://engineering.paiza.io/entry/2015/03/12/145216
*/
class MyApp extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {
firstName: this.props.firstName,
lastName: this.props.lastName,
};
}
handleChange({ target }) {
this.setState({
[target.id]: target.value,
});
}
render() {
const fullName = `${this.state.firstName} ${this.state.lastName}`;
return <div>
First name:&nbsp;
<input
id="firstName"
onChange={this.handleChange}
value={this.state.firstName}
/><br />
Last name:&nbsp;
<input
id="lastName"
onChange={this.handleChange}
value={this.state.lastName}
/><br />
Full name: {fullName}
</div>
}
}
React.render(<MyApp firstName="Taro" lastName="Yamada" />, document.body);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment