Last active
March 3, 2017 19:49
-
-
Save leonardovillela/8604b69dce9dbf354955b3062e037e36 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
class TwoWayBindingInput extends React.Component { | |
state = { | |
value: this.props.value | |
}; | |
componentWillReceiveProps(nextProps) { | |
if (this.state.value !== nextProps.value) | |
this.setState({value: nextProps.value}); | |
} | |
onChange(event) { | |
const { value } = event.target; | |
this.setState({value}); | |
if (this.props.onChange) this.props.onChange(event); | |
} | |
render() { | |
return <input type="text" onChange={::this.onChange} value={this.state.value} /> | |
} | |
} | |
class MainPage extends React.Component { | |
state = { | |
value: '' | |
}; | |
handleChange(event) { | |
const { value } = event.target; | |
this.setState({value}); | |
} | |
render() { | |
return ( | |
<div> | |
<TwoWayBindingInput onChange={::this.handleChange} value={this.state.value} /> | |
<br/> | |
<TwoWayBindingInput onChange={::this.handleChange} value={this.state.value} /> | |
</div> | |
); | |
} | |
} | |
export default MainPage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That's pretty useful, buddy, thanks a lot.