Updating a React Input text field with the value on onBlur event

Suthan Bala picture Suthan Bala · Jan 24, 2017 · Viewed 79.2k times · Source

I have the following input field as below. On blur, the function calls a service to update the input value to the server, and once that's complete, it updates the input field.

How can I make it work? I can understand why it's not letting me change the fields but what can I do to make it work?

I can't use the defaultValue because I will be changing these fields to some other ones

<input value={this.props.inputValue} onBlur={this.props.actions.updateInput} />

Answer

Shubham Khatri picture Shubham Khatri · Jan 24, 2017

In order to have the input value editable you need to have an onChange handler for it that updates the value. and since you want to call a function onBlur, you have to bind that like onBlur={() => this.props.actions.updateInput()}

componentDidMount() {
   this.setState({inputValue: this.props.inputValue});
}
handleChange = (e) => {
  this.setState({inputValue: e.target.value});
}

<input value={this.state.inputValue} onChange={this.handlechange} onBlur={() => this.props.actions.updateInput(this.state.inputValue)} />