Skip to content

Instantly share code, notes, and snippets.

@leonardovillela
Last active March 3, 2017 19:49
Show Gist options
  • Save leonardovillela/8604b69dce9dbf354955b3062e037e36 to your computer and use it in GitHub Desktop.
Save leonardovillela/8604b69dce9dbf354955b3062e037e36 to your computer and use it in GitHub Desktop.
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;
@igordonin
Copy link

That's pretty useful, buddy, thanks a lot.

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