Skip to content

Instantly share code, notes, and snippets.

@markerikson
Created August 2, 2017 02:53
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save markerikson/cc70c575d41b30c5b3bcc242dc8f7cca to your computer and use it in GitHub Desktop.
Save markerikson/cc70c575d41b30c5b3bcc242dc8f7cca to your computer and use it in GitHub Desktop.
React controlled input with internal state example
class ControlledInputWithInternalState extends Component {
constructor(props) {
super(props);
this.state = {
isValid : true,
value : props.value
};
}
componentWillReceiveProps(nextProps) {
if(nextProps.value !== this.props.value) {
// new value from the parent - copy it to state
this.setState({value : nextProps.value});
}
}
onValueChanged = (e) => {
const {value} = e.target;
// No empty strings
const isValid = value !== "";
this.setState({value, isValid}, this.onStateUpdated);
}
onStateUpdated = () => {
if(this.state.isValid) {
this.props.onChange(this.state.value);
}
}
render() {
const {value, isValid} = this.state;
let errorMessage = null;
if(!isValid) {
errorMessage = <div>Oops!</div>
}
return (
<div>
<input
type="text"
name="theInput"
value={value}
onChange={this.onValueChanged}
/>
{errorMessage}
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment