I want to change input text value using state and React value property and also make the field editable.
My component's constructor:
constructor(props) {
super(props);
// States
this.state = {
value: this.props.object.subtext
};
this._handleChange = this._handleChange.bind(this);
}
My render() function:
return (
<input
type={this.props.object.type}
value={this.props.object.subtext}
onChange={this._handleChange}
/>
);
componentDidUpdate() function:
componentDidUpdate() {
if (this.state.value !== this.props.object.subtext) {
this.setState({value: this.props.object.subtext});
}
}
And for _handleChange(e) function:
_handleChange(e) {
this.props.object.subtext = e.target.value;
this.componentDidUpdate(); // not sure it's right or not
}
The code works fine, but I'm a little bit unsure that was the best practice or not because I recalled this.componentDidUpdate() manually inside the event handler function.
I did it to fix my previous bug which is the value of input component won't be updated when the state was changed.
I want to know whether what I'm doing is right or not, any comments or answers will be appreciated.