How to create input field in Alert dialog in iOS React Native?

Table of Contents Hide
  1. Code Example
    1. Live Demo
  2. Conclusion

React Native provides prompt() function to create input field in the dialog. You can provide title, message, buttons, callback function, default input value, keyboard type etc.

This functionality is specific to iOS so it won’t work in Android phones.

The prompt() structure looks like this –

Alert.prompt(title, message, callbackOrButtons, type, defaultValue, keyboardType)

Here we have 6 different parameters –

  1. title – A title of the prompt
  2. message – A description text which displays above input field
  3. callbackOrButtons – Either a function which get the input field text as argument or the array of buttons.
  4. type – Type of input field. Possible values are – default, plain-text, secure-text, login-password.
  5. defaultValue – A default input field value.
  6. keyboardType – Type of keyboard. It restricts the type of data you want users to input like numerics, email, phone number etc. The possible values are – number-pad, decimal-pad, numeric, email-address, phone-pad, url.

Code Example

import React, { useState } from "react";
import { View, StyleSheet, Button, Alert, Text } from "react-native";

const App = () => {
  const [message, setMessage] = useState("")
  
  const textInputAlert = () =>
    Alert.prompt(
      "Alert Title",
      "Write your name here -",
      [
        {
          text: "Cancel",
          onPress: () => console.log("Cancel Pressed"),
          style: "cancel"
        },{
          text: "Ok",
          onPress: (text) => setMessage(text),
        },
      ],
      'plain-text'
    );

  const textInputAlertWithDefault = () =>
    Alert.prompt(
      "Alert Title",
      "Input field has default value - akashmittal.com",
      [
        {
          text: "Cancel",
          onPress: () => console.log("Cancel Pressed"),
          style: "cancel"
        },{
          text: "Ok",
          onPress: (text) => setMessage(text),
        },
      ],
      'plain-text',
      'akashmittal.com'
    );

  const textInputAlertWithCallbackFunction = () =>
    Alert.prompt(
      "Alert Title",
      "Input text will process by callback function",
      (text) => setMessage(text),
      'plain-text'
    );

  const phoneNumberAlert = () =>
    Alert.prompt(
      "Alert Title",
      "Write phone number here -",
      (text) => setMessage(text),
      'plain-text',
      undefined,
      'phone-pad'
    );

  const secureTextAlert = () =>
    Alert.prompt(
      "Alert Title",
      "Input field text will not display -",
      (text) => setMessage(text),
      'secure-text'
    );

  const loginPasswordAlert = () =>
    Alert.prompt(
      "Alert Title",
      "Login-Password",
      ({login, password}) => setMessage(JSON.stringify({login, password})),
      'login-password'
    );

  return (
    <View style={styles.container}>
      <Text style={{fontSize: 20}}>Input Message: {message}</Text>
      <Button title={"Show Prompt"} onPress={textInputAlert} />
      <Button title={"Show Prompt With Default Input Value"} onPress={textInputAlertWithDefault} />
      <Button title={"Show Prompt With Callback Function"} onPress={textInputAlertWithCallbackFunction} />
      <Button title={"Show Prompt For Phone Number"} onPress={phoneNumberAlert} />
      <Button title={"Show Prompt For Secure Text"} onPress={secureTextAlert} />
      <Button title={"Login-Password Prompt"} onPress={loginPasswordAlert} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "space-around",
    alignItems: "center",
    paddingVertical: 100
  }
});

export default App;

Output –

simple text input in alert dialog in react native

The above image shows the output of first button click which we declared in line 79 in our code. This one is running textInputAlert() function. It displays the Alert box prompting for an input. We declared two buttons – Cancel and Ok. Ok button is getting input field text in onPress function. We are then storing the field value in a state variable and displaying in Text View.

setting default value of input field in alert dialog in react native

This is the output of 2nd button click. Everything is same as first function but here we are setting the default value in input field.

getting text value in callback function in prompt alert in react native

In this output, we clicked the third button where we are processing the input data using callback function. So, instead of using buttons for callbackOrButtons field in prompt(), we are using callback function.

phone number input field in alert dialog in react native

This is the output of fourth button click. Here the keyboardType is changed to phone-pad. So, it is displaying only numeric keyboard.

secure input field for passwords in alert dialog in react native

This image is of fifth button click. Here the alert box is showing the password field. We are getting this because of setting type=secure-text.

login-password input field in alert dialog

This output is of the sixth button where we are displaying the login and password fields. You get this by setting type=login-password. Now since the fields are more than one, so callback function will get the object {login, password}.

Live Demo

Open Live Demo

Conclusion

Having input fields in Alert dialog is a helpful feature which is provided in iOS only. If you want full attention of user, you use Alert dialogs but at the same time if you need users to fill some important field, then you can use prompt(). In this whole article we covered a number of features and cases.


React Native Series

Alert

  1. Basic Alert
  2. Dismiss on Clicking Outside
  3. Input Fields in Alert Dialog – Prompt()
  4. Dark-Light Theme of Dialog

ActivityIndicator

  1. Basic Circular Loader
  2. Change size of Circular Loader
  3. Show/hide Circular Loader
  4. Change color of Circular Loader

Button

  1. Simple Button
  2. Change Button Color
  3. Disable Button Click
  4. Disable touch sound on Button click

FlatList

  1. Simple List
  2. Single Item Selection from List
  3. Multiple Item Selection from List
  4. Adding separator between list items
  5. Multiple columns List
  6. Showing Message in Empty List
  7. Add Footer to the List
  8. Add Header to the List
  9. Horizontal List
  10. Inverted List
  11. Pull to Refresh in List
  12. Infinite Loading List

SectionList

  1. Section List

ScrollView

  1. ScrollView
  2. Stick Single Item at Header
  3. Stick Multiple Items at Header
  4. Stick Item at Footer
  5. Hide Sticky Element on Scroll

Image

  1. Display Image from remote url
  2. Display local storage image
  3. Display Base64 Image
  4. Display Gif & Webp Images
  5. Adding Blur to Image
  6. Displaying loader for Image
  7. Resizemode for Images
  8. Setting Default Placeholder Image
  9. Background Image

Modal

  1. Basic Modal
  2. Slide from bottom Modal
  3. Fade In Modal
  4. Transparent Overlay Modal

RefreshControl

  1. RefreshControl
  2. Change Refresh Loader Color
  3. Change Refresh Loader Size
  4. Change Refresh Loader Background Color
  5. Title under Refresh Loader
  6. Change color of title under refresh loader

StatusBar

  1. Get StatusBar Size
  2. Change StatusBar Background Color
  3. Display StatusBar icons & text in While Color
  4. Display StatusBar icons & text in Dark Color
  5. Hiding StatusBar
  6. Translucent StatusBar

Switch

  1. Simple Switch
  2. Disable Switch
  3. Change Switch Colors

Text

  1. Adding Text
  2. Bold Text
  3. Italic Text
  4. Underline Text
  5. Selecting Text for copy-paste
  6. Changing Highlight Color of Text Selection
  7. Fit text in View box
  8. Clickable anchors in text
  9. Truncate Lengthy Text

TextInput

  1. Simple Input Field
  2. Auto Capitalize Text in Input Field
  3. Multiline Input Field
  4. Hide Cursor in Input Field
  5. Clear input Field using X
  6. Clear input Field when focused
  7. Change Cursor Color in Input Field
  8. Disable input field
  9. Icon at the left of Input Field
  10. Dark-Light Keyboard
  11. Avoid Overlapping of Keyboard
  12. Limiting Characters in Input Field
  13. Numeric Keyboard
  14. Email Id Keyboard
  15. Phone number Keyboard
  16. Url Keyboard
  17. Placeholder in input field
  18. Placeholder Color in Input Field
  19. Password Input Field
  20. Programmatically select text in Input Field
  21. Change Text Selection Color in Input Field
  22. Select Whole text in Input Field on Focus
  23. Write text from center in input field
  24. Changing underline color of input field

TouchableWithoutFeedback

  1. TouchableWithoutFeedback

TouchableHighlight

  1. TouchableHighlight

TouchableOpacity

  1. TouchableOpacity

Pressable

  1. Pressable
  2. Creating Ripple Effect

Appearance

  1. Dark-Light System Color Scheme

AppState

  1. AppState – Foreground/Background State of App

ToastAndroid

  1. Creating Android Toast Message

Dimensions

  1. Getting Screen & Window Dimensions

Keyboard

  1. Dismiss Keyboard Programmatically

👉 Learn Material Design using React Native Paper