Monday, June 3, 2024
49
rated 0 times [  52] [ 3]  / answers: 1 / hits: 18440  / 5 Years ago, thu, january 31, 2019, 12:00:00

In React Native, we have the option to use an Alert to notify the user in a popup. These 'simple' Alerts can be composed with:



Alert.alert('Hello world!')



Which produces an Alert with a message, no title, and an OK button.



You can also make 2 or 3 button Alerts, which are composed as follows (2 button example):



Alert.alert(
'Alert Title',
'My Alert Msg',
[
{
text: 'Ask me later',
onPress: () => console.log('Ask me later pressed')
},
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{
text: 'OK',
onPress: () => console.log('OK Pressed')
},
],
{cancelable: false},
);


Notice here you have the options for an onPress function for the buttons



What I am wondering is if I can apply an onPress for the first case, when 'OK' is pressed, but there is no example (or any details really!) in the official docs



Perhaps it is not (yet) possible. Can anyone confirm or deny?


More From » react-native

 Answers
19

You can create an Alert with only one button. You can then decide what happens when you press OK.



https://facebook.github.io/react-native/docs/alert




iOS



On iOS you can specify any number of buttons. Each button can
optionally specify a style, which is one of 'default', 'cancel' or
'destructive'.



Android



On Android at most three buttons can be specified. Android has
a concept of a neutral, negative and a positive button:




  • If you specify one button, it will be the 'positive' one (such as 'OK')

  • Two buttons mean 'negative', 'positive' (such as 'Cancel', 'OK')

  • Three buttons mean 'neutral', 'negative', 'positive' (such as 'Later',
    'Cancel', 'OK')




So if you only want one button then you can do something like this.



Alert.alert(
'Alert Title',
'My Alert Msg', // <- this part is optional, you can pass an empty string
[
{text: 'OK', onPress: () => console.log('OK Pressed')},
],
{cancelable: false},
);


If you use Alert.alert('Hello world!') without passing any options to it then there is no way to define what happens when you press OK the only way to do that is to do something like I have show above. If you want it to look the same on the screen, then just pass an empty string for the message. Both the title and the message can be empty strings, though you probably don't want both to be that at the same time.


[#52678] Saturday, January 26, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryderalfonsos

Total Points: 655
Total Questions: 88
Total Answers: 91

Location: Nauru
Member since Thu, Feb 2, 2023
1 Year ago
ryderalfonsos questions
Mon, Sep 9, 19, 00:00, 5 Years ago
Wed, Feb 13, 19, 00:00, 5 Years ago
Tue, Feb 12, 19, 00:00, 5 Years ago
Fri, Dec 28, 18, 00:00, 6 Years ago
;