Alert buttons
- React Native course
- Beginner
- Lesson 95/116
- 5 min
Learn alert buttons and callbacks.
Alert buttons
By default Alert.alert shows a single OK button. To add your own buttons you pass an array as the third parameter. Each button is an object with text and onPress properties.
Alert.alert('Save', 'Save changes?', [
{ text: 'Cancel', onPress: () => {} },
{ text: 'Save', onPress: () => save() }
]);Buttons are laid out left to right in array order. On iOS at most three buttons are shown; on Android the limit is more flexible.
The onPress callback
The onPress property of each button object is a function called when the user presses that button. Inside this function you do whatever you want: save data, change navigation or update state.
For a cancel button you usually provide an empty function: onPress: () => {}. For a confirm button you provide the function that does the actual work. After a button is pressed the Alert closes automatically; you do not need to write closing code.
Practice Your turn: Alert with two buttons
Call Alert.alert with title 'Exit' and message 'Do you want to exit?'. Add two buttons: Cancel and Exit. Give each an onPress.
Starter code
import { Alert, Button } from 'react-native';
function Screen() {
return (
<Button
title="Exit"
onPress={() => {
// show an Alert with two buttons
}}
/>
);
}Sample solution
import { Alert, Button } from 'react-native';
function Screen() {
return (
<Button
title="Exit"
onPress={() =>
Alert.alert('Exit', 'Do you want to exit?', [
{ text: 'Cancel', onPress: () => {} },
{ text: 'Exit', onPress: () => doExit() }
])
}
/>
);
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: button object
{ text: 'OK', ____: () => save() }
{ text: 'OK', onPress: () => save() }
Explanation: onPress is called when the button is pressed.
2 Which property is required in an Alert button object?
{ text: 'Save', onPress: () => save() }- color
- text Correct answer
- style
- icon
Explanation: text sets the button label and is required.
3 Match: button property and role
| Term | Meaning |
|---|---|
text |
button label |
onPress |
press handler function |
style |
button appearance |