Forked from markerikson/ReactControlledInputWithState.jsx
Created
April 14, 2018 21:03
-
-
Save barbagrigia/e9f698288005b43d3d490da1f5adcbb7 to your computer and use it in GitHub Desktop.
React controlled input with internal state example
This file contains hidden or 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
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