In this tutorial, we'll show a quick way to request user information using Prompts.
- Next post ↑
- StatusBar in React Native
- Previous post ↓
- Alert in React Native
What is the Prompt?
Alert.prompt()
, in React Native, is used to get information from a user in a native popup, similar to Alert.alert()
. This option is only available on iOS devices.
plain-text
Similar to Alert.alert()
, the first 3 arguments are the same: title
, message
, and buttons
. The next argument is used to provide the prompt type.
Available prompt types:
plain-text
- Plain text input prompt (default)secure-text
- Secure text input promptlogin-password
- Login and password prompt
import { Alert } from 'react-native';
Alert.prompt(
'Username',
'Enter your new username below',
[
{text: 'Cancel', style: 'destructive', onPress: () => {}},
{
text: 'Submit',
onPress: (username) => {
// update username
}
},
],
'plain-text',
);
secure-text
Secure prompt, just like secure TextInput
, is usually used for password fields.
It is common for mobile apps to prompt user enter their password when performing high-security actions (like changing emails) to prevent account fraud.
const confirmPassword = () =>
new Promise(resolve =>
Alert.prompt(
'Confirm Password',
'Enter your current password for confirmation',
[
{text: 'Cancel', style: 'destructive', onPress: () => resolve(null)},
{text: 'Confirm', onPress: resolve},
],
'secure-text',
),
);
<TouchableOpacity
onPress={async () => {
const currentPassword = await confirmPassword()
if (currentPassword) {
// verify password
}
}}>
<Text>Confirm Password</Text>
</TouchableOpacity>
login-password
Lastly, Apple has created a way to enter both username and password in a single prompt.
const signInPrompt = () =>
new Promise(resolve =>
Alert.prompt(
'Sign In',
'Enter your credentials to log in:',
[
{text: 'Cancel', style: 'destructive', onPress: () => resolve(null)},
{text: 'Sign In', onPress: resolve},
],
'login-password',
),
);
<TouchableOpacity
onPress={async () => {
const credentials = await signInPrompt();
if (credentials) {
const {login, password} = credentials;
// sign in
}
}}>
<Text>Sign In</Text>
</TouchableOpacity>
Default Value
If you need to provide a default value for the prompt, you can pass it as a 5th argument after the prompt type as shown below:
import { Alert } from 'react-native';
const defaultValue = `withframe`;
Alert.prompt(
'Username',
'Enter your new username below',
[
{text: 'Cancel', style: 'destructive', onPress: () => {}},
{
text: 'Submit',
onPress: (username) => {
// update username
}
},
],
'plain-text',
defaultValue
);
We hope you enjoyed this content and now better understand how to use Prompt in React Native.