Hizqeel Javed
Hizqeel Javed

Reputation: 91

How to use foreach inside Alert.alert in react native

function openmodal(modalarray) {
  return Alert.alert(
    "Alert Title",
    "My Alert Msg",
    [
      modalarray.forEach(element => {
        "{text: element, onPress: () => console.log('button press)},";
      })
    ],
    { cancelable: false }
  );
}

Upvotes: 2

Views: 1139

Answers (2)

Jun Jie
Jun Jie

Reputation: 51

Try:

function openmodal(modalarray) {
  return Alert.alert(
    "Alert Title",
    "My Alert Msg",
    modalarray.map(element => ({
      text: element,
      onPress: () => console.log('button press')
    })),
    { cancelable: false }
  );
}

Upvotes: 1

Prasun
Prasun

Reputation: 5023

Please use .map function instead of .forEach. .forEach doesn't return any value, hence you are just passing undefined in the array.

Consider the following example

function openmodal(modalarray) {
  return Alert.alert(
    "Alert Title",
    "My Alert Msg",
    [
      ...modalarray.map(element =>
        ({text: element, onPress: () => console.log('button press')}))
    ],
    { cancelable: false }
  );
}

Hope this will help!

Upvotes: 2

Related Questions