Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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} />

like image 736
Suthan Bala Avatar asked Jan 24 '17 15:01

Suthan Bala


People also ask

How do you use onBlur event in react JS?

onBlur triggers when focus is lost from the input element in context. In React. js, we bind event handlers by passing a method defined in the component to be called accordingly. .bind(this) is called in order to retain the value of this and expose component methods within the event handler function such as this.

What is the difference between onChange and onBlur?

onChange is when something within a field changes eg, you write something in a text input. onBlur is when you take focus away from a field eg, you were writing in a text input and you have clicked off it.

How do you Unfocus input React?

To unfocus a TextInput in React Native, we can use the Keyboard. dismiss method. to set the onSubmitEditing prop to Keyboard. dismiss .


2 Answers

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)} /> 
like image 162
Shubham Khatri Avatar answered Sep 20 '22 23:09

Shubham Khatri


Ways of doing this:

  1. Do not assign value property to input field, whenever onblur method gets trigger, hit the api like this:

    <input placeholder='abc' onBlur={(e)=>this.props.actions.updateInput(e.target.value)} /> 

Update value to server:

updateInput(value){     /*update the value to server*/ } 
  1. If you are assigning the value property to input field by this.props.inputValue, then use onChange method, pass the value back to parent component, change the inputValue by using setState in parent, it will work like this:

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

In Parent Component:

onChange(value){     this.setState({inputvalue:value}); } 

Update value to server:

updateInput(value){     /*update the value to server*/ } 
like image 26
Mayank Shukla Avatar answered Sep 19 '22 23:09

Mayank Shukla