Given the React component with controlled input, I would like to be able to:
- Set input value from parent state
- Allow user to change input to any value
- Update the parent state only after the user submits and validates the input.
I can execute 1 and 2 with the snippet below, but since the value appeared in ChildComponent through the details, I am not sure how to change the input value without changing the myInput value on the parent.
class ChildComponent extends React.Component
{
render(){
return <input type="text" value={this.props.inputValue} onChange={this.handleChange.bind(this)} />
}
handleChange(e){
this.props.onInputChange(e.target.value);
}
handleSubmit(){
// do some validation here, it it passes...
this.props.handleSubmit();
}
}
class ParentComponent extends React.Component{
constructor(){
super();
this.state = {myInput: ""};
}
render(){
return <ChildComponent inputValue={this.state.myInput} onInputChange={this.handleChange.bind(this)} />
}
handleChange(newValue){
this.setState({myInput: newValue});
}
handleSubmit(){
// do something on the server
}
}
source
share