Home > Enterprise >  React Native CustomAlert does not work inside onPress
React Native CustomAlert does not work inside onPress

Time:04-19

I'm facing a weird problem. In my react native app I have customAlert, which shows if the statement is false, currently it shows only the console. I tried testing and showing my CustomAlert but not inside onPress it works fine like the image below. but inside onPress does not work. What am I missing here?

enter image description here

    import CustomAlert from '../components/CustomAlert';
    const [modalVisible, setModalVisible] = useState(false);

    <View style={{ marginTop: `30%`, alignItems: 'center' }}>
        <GoogleSigninButton
          style={{ width: 252, height: 58 }}
          size={GoogleSigninButton.Size.Wide}
          color={GoogleSigninButton.Color.Dark}
          onPress={() => {
            if (fingerprint === true) {
              googleLogin();
            }
            else {
              console.log("Alert should pop up");

              <CustomAlert
                modalVisible={modalVisible}
                setModalVisible={setModalVisible}
                title={'Message'}
                message={'Please enable your Touch ID/PIN to your device'}
                buttons={[{
                  text: 'Ok',
                  func: () => { console.log('Yes Pressed') }
                }]}
              />

            }
          }
          }
        />
    </View>

CodePudding user response:

You could try moving your <CustomAlert> outside of the <GoogleSignInButton> and then display the <CustomAlert> conditionally based on your modalVisible state variable:

import CustomAlert from '../components/CustomAlert';
const [modalVisible, setModalVisible] = useState(false);

<View style={{ marginTop: `30%`, alignItems: 'center' }}>
    <GoogleSigninButton
      style={{ width: 252, height: 58 }}
      size={GoogleSigninButton.Size.Wide}
      color={GoogleSigninButton.Color.Dark}
      onPress={() => {
        if (fingerprint === true) {
          googleLogin();
        }
        else {
          console.log("Alert should pop up");
          setModalVisible(true);
        }
      }
      }
    />
    <CustomAlert
        modalVisible={modalVisible}
        setModalVisible={setModalVisible}
        title={'Message'}
        message={'Please enable your Touch ID/PIN to your device'}
        buttons={[{
          text: 'Ok',
          func: () => { console.log('Yes Pressed') }
        }]}
    />
</View>

Notice that inside the else branch we call setModalVisible(true) which will set modalVisible to true. Then modalVisible gets passed as a prop to <CustomAlert>, which should tell the modal to render (assuming it is set up properly).

  • Related