Search code examples
reactjsreact-nativemodal-dialoguse-effectuse-state

How to close modal when navigating back to my screen?


So I have a homescreen that renders a modal component. I use some states for modal visibility. However, the problem is that when I navigate from the modal to another screen and then back to my home screen, the modal is still opened and I cannot figure out how to close it. I tried using useEffect but it does not do anything. Any tips?

This is home screen. The AddButton component is a simple TouchableOpacity that onPress call the toggleModal function

const [isModalVisible, setIsModalVisible] = useState(false);

 const toggleModal = () => {
      setIsModalVisible(!isModalVisible);
  };

useEffect(() => {
    setIsModalVisible(false)
  }, [navigation])

return (
    <AddButton
      title="ADD BOOK"
      toggleModal={toggleModal}
    />
)

And the Modal Component is this:

const ModalComponent = ({navigation, isModalVisible, toggleModal, title, author, save, onNavigate }) => {
  
  return (
    <Modal isVisible={isModalVisible}>
      <View style={styles.container}>
        <Text>Modal</Text>

        <View style={styles.footer}>
          <TouchableOpacity onPress={toggleModal}>
            <Text>Cancel</Text>
          </TouchableOpacity>

          <TouchableOpacity onPress={() => navigation.navigate("AddBookScreen")}>
            <Text>{save}</Text>
          </TouchableOpacity>
        </View>
        
      </View>
    </Modal>
  );
};

Solution

  • Modify this code

     <TouchableOpacity onPress={() => navigation.navigate("AddBookScreen")}>
                <Text>{save}</Text>
              </TouchableOpacity>
    

    to

    <TouchableOpacity onPress={() => {
        navigation.navigate("AddBookScreen")
        toggleModal();
      }}>
                <Text>{save}</Text>
              </TouchableOpacity>