Using AlertIOS.prompt in React Native

AlertIOS.prompt accepts a couple of parameters. Let's take a look at them:

'Title', 'Default Value', 
[{text: 'Button One', onPress: this.firstButtonPress.bind(this)}, 
{text: 'Button Two', onPress: this.secondButtonPress.bind(this)}]

The first parameter that AlertIOS.prompt accepts is the title -- what gets displayed to the user. It's a required propType.

The next parameter is a value, which is what gets pre-filled into the text box for your user. This is an optional propType.

After that, the array you see maps to the buttons that your user gets to tap on. These buttons are represented as objects, with some key/value pairs. The first is text, which will display the button text. The second is onPress, which is a method that you specify to handle that specific button being pressed.

In order to retrieve the value of the button, you need to bind this (in this case, it's the prompt) to your onPress method. If you do this, you can have your onPress handler access the typed in value as such:

firstButtonPress(value) {

This button array is conditionally optional. If you choose not to give a list of buttons, AlertIOS will expect you to pass in a callback function as a parameter for AlertIOS.prompt (but not both a set of buttons and a callback).

P.S. I wrote a book on React Native development! It's titled React Native By Example and is available for purchase on Amazon. It's a fantastic resource for React Native development and if you're interested in leveling up your skills, I strongly recommend checking it out!

Show Comments