Home > OS >  React Native Modal is not hiding
React Native Modal is not hiding

Time:01-01

I am implementing my own Modal, trying to replace the Alert.alert with something more beautiful. I made it to be displayed when needed, but it is not hiding on the button press, but I think I transferred it the needed function. My modal structure is the following:

export const RCModal = ({ title, visible, onButtonPress }) => {
  return (
    <Modal
      animationType='fade'
      transparent={true}
      visible={visible}
    >
      <View style={styles.container}>
        <Text style={styles.title}>{title}</Text>
        <Pressable style={styles.button} onPress={onButtonPress}>
          <Text style={styles.text}>OK</Text>
        </Pressable>
      </View>
    </Modal>
  )
};

And it is used in the application in the following way:

// ...
  const [alertVisible, setAlertVisible] = useState(false);
  const [alertTitle, setAlertTitle] = useState();
  const [alertOnPress, setAlertOnPress] = useState();
// ...
  const winner = (theWinner) => {
    setBlocked(true);
    setAlertTitle(`${theWinner} win!`);
    setAlertOnPress(() => setAlertVisible(!alertVisible));
    setAlertVisible(true);
  }
// ...
  return (
    <View style={styles.container}>
      <RCModal title={alertTitle} visible={alertVisible} onButtonPress={alertOnPress} />
      <ScrollView contentContainerStyle={{ flexGrow: 1, justifyContent: 'center' }}>
        <Text style={styles.title}>Noughts and Crosses</Text>
        <Text style={styles.tip}>Get {winCondition()} in row, column or diagonal</Text>
        <View style={styles.buttonsContainer}>
          <Text style={styles.turnContainer}>Turn: <Text style={[styles.turn, { color: turn === 'X' ? '#2E86C1' : '#E74C3C'}]}>{turn}</Text></Text>
          <TouchableHighlight underlayColor="#000000" style={[styles.button, styles.newGameButton]} onPress={setInitialFieldState}>
            <Text style={styles.buttonText}>New game</Text>
          </TouchableHighlight>
        </View>
        <Field state={fieldState} size={fieldSize} onCellPress={onCellPress} />
      </ScrollView>
      <View style={styles.settingsButtonContainer}>
        <TouchableHighlight underlayColor={theme.colors.secondary} style={styles.settingsButton} onPress={onSettingsPress}>
          <Image source={require('../img/settings.png')} style={styles.settingsIcon} />
        </TouchableHighlight>
      </View>
    </View>
  );
};

When the winner() is called, it is displayed as it should, but when I press OK button, it is not hiding. How can I fix it?

CodePudding user response:

The answer was that to set a function like a state variable, I needed to set it like setAlertOnPress(() => () => setAlertVisible(false)) (2 x () =>)

CodePudding user response:

You can use setAlertVisible to change the alertVisible state:

<RCModal title={alertTitle} visible={alertVisible} onButtonPress={() => setAlertVisible(false)} />
  • Related