TextInput with value doesn't change value

Viewed 13500

In my react-native app i have an API that I'm retrieving data from, and I'm setting the data inside my input values, user should be able to edit those inputs and update, but when i try to type in the input it won't type anything and the value stays as it is, here is the TextInput code:

<TextInput
   placeholder= Email
   value={this.state.info.email}
   onChangeText={email => this.setState({ email })}/>
6 Answers

Since I don't think email is the only prop of your state.info I recommend you to use setState() properly, in order to modify just that field. According to immutability and ES6, something like:

<TextInput
  placeholder="Email"
  value={this.state.info.email}
  onChangeText={text =>
    this.setState(state => ({
      info: {
        ...state.info,
        email: text
    }))
  }
/>;

Read more about handling TextInput here

I was having the same issue until I changed the value prop to defaultValue like this:

<TextInput
   style={styles.inputBox}
   onChangeText={title => this.setState({ title })}
   defaultValue={this.state.title}
   placeholder='Title'
/>

I found this info on React's documentation here

first you need to declare the state and then apply that state to TextInput Value.

state: {
     email: ''
}

and to populate TextInput for first time with the API value you have to add

componentDidMount(){
  this.setState({email: this.props.info.email});
}

and your TextInput will be like below:

<TextInput
   placeholder= Email
   value={this.state.email}
   onChangeText={value=> this.setState({ email: value})}/>

Hope this works..

I am also having the same issue until I changed the value prop to defaultValue like this:

<TextInput
   style={styles.inputBoxSize}
   onChangeText={title => this.setState({ title })}
   defaultValue={this.state.title}
   placeholder='Title'
/>

value={this.state.title} - instead of this

defaultValue={this.state.title} - use this one

Thats all. Enjoy your coding...

I think you have an error in your handler function. When you called setState you updated the this.state.email but in your text input value you used this.state.info.email, you also wrote the event object to the email, instead of the new value of the field (event.target.value). You should use something like this.

onChangeHandler = event => {
  const newEmail = event.target.value
  this.setState({ info: {email: newEmail})}
}

<TextInput
  placeholder= Email
  value={this.state.info.email}
  onChangeText={this.onChangeHandler.bind(this)} />

I don't know whether it is a good approach or not but Dustin Spengler answer worked for me without any problem. I don't have enough reputation to upvote and to comment.

<TextInput
style={styles.inputBox}
onChangeText={title => this.setState({ title })}
defaultValue={this.state.title}
placeholder='Title'
/>
Related