Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Alert in React Native - function on press

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?

like image 340
fullStackChris Avatar asked Dec 11 '22 03:12

fullStackChris


1 Answers

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.

like image 78
Andrew Avatar answered Dec 14 '22 23:12

Andrew