5

I have a TextInput component that calls an 'OnChangeText' event :

<TextInput onChangeText={(text) => this.setState({zip:text})}/>

That works fine.

Now I want to change the call event to a function:

 <TextInput onChangeText={_handleTextChange}/>

_handleTextChange(event) {
       this.setState({zip: 
       event.nativeEvent.text});

  }

That doesn't work. I get the following error :

undefined is not an object (evaluating 'event.nativeEvent.text'

How do send the 'Event' object to _handleTextChange function?

Thanks, Yaron

1
  • You should choose an answer as accepted. Good question though. Helped me too.
    – MarAvFe
    Commented Sep 28, 2017 at 6:02

1 Answer 1

14

onChangeText passes a string to your handler function instead of an Event.

class YourComponent {
   render () {
     // ...
     return <TextInput onChangeText={this._handleTextChange.bind(this)}/>;
   }

  _handleTextChange(text) {
     this.setState({zip: text});
  }
}

EDIT

If you want an Event instead of text string, you can use onChange instead of onChangeText.

class YourComponent {
   render () {
     // ...
     return <TextInput onChange={this._handleTextChange.bind(this)}/>;
   }

  _handleTextChange(event) {
     this.setState({zip: event.nativeEvent.text});
  }
}
3
  • Thank you! It worked. Can you please point me to a website that has the details of each event and what object is passes?
    – Yaron
    Commented Jul 3, 2016 at 7:57
  • 2
    You're welcome! I looked at the official document. It lacks the details and I had to guess from the examples though. Commented Jul 4, 2016 at 8:54
  • If you're interested, you can look at its source code. Commented Jul 4, 2016 at 8:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.