Home > OS >  React-Native Alert: Dynamically set two or three buttons in the alert
React-Native Alert: Dynamically set two or three buttons in the alert

Time:05-05

I need to set up an alert in React-Native (I'm also using Expo, if that matters here) but I'd like to set it so it will show 2 or 3 buttons based on data I send to it. A simple example would be:

import { Alert } from 'react-native';

const showConfirmationAlert = (val) => {
  return Alert.alert(
    "Alert title",
    "Alert text",
    [
      val !== null ? { text: "Option A", onPress: () => { ... } } : {},
      { text: "Option B", onPress: () => { ... } },
      { text: "Cancel"}
    ]
  );
};

Right now, this works but if val === null, 3 options still show except option A is empty. I can't set the option A else condition to null, i.e. val !== null ? { text: "Option A", onPress: () => { ... } } : null as that throws an error that objects cannot be null.

I can certainly run the val === null check prior to calling the Alert and simply create two Alerts, one for each case, but I'd like to know if it's possible to set up this system and have it all within a single Alert.

I can also do the following:

import { Alert } from 'react-native';

const showConfirmationAlert = (val) => {
  return Alert.alert(
    "Alert title",
    "Alert text",
    val !== null
      ? [
        { text: "Option A", onPress: () => { ... } } : {},
        { text: "Option B", onPress: () => { ... } },
        { text: "Cancel"}
      ]
      : [
        { text: "Option B", onPress: () => { ... } },
        { text: "Cancel"}
      ]
  );
};

But it seems there's too much repeating of code.

Is there a way to achieve this without either having two completely different alerts or repeating the two options that will always be shown?

CodePudding user response:

How do you like this solution?

import { Alert } from 'react-native';

const showConfirmationAlert = (val) => {

    const options = [{
        { text: "Option B", onPress: () => { ... } },
        { text: "Cancel"}
    }];

    if (val !== null) {
        options.unshift({ text: "Option A", onPress: () => { ... } });
    }

    return Alert.alert(
        "Alert title",
        "Alert text",
        options,
    );
};

You could even rename options to something like "baseOptions" and create a method that handles corner cases. At this moment you only have one corner case which is related to when val is null, but you could have more in the future.

  • Related