How to make a Modal Toggle when using Route and Navigation?

Viewed 42

I have four pages, "ReadyScreen" "RunningScreen" "ListScreen" and "CheckScreen"

To start a run, the user navigates from the "ReadyScreen" to the "ListScreen" to the "CheckScreen" and lastly to the "RunningScreen"

ReadyScreen -> ListScreen -> CheckScreen -> RunningScreen

At the end of the user's run, they are navigated back to the "ReadyScreen" from the "RunningScreen"

I want a Modal to toggle with their running info, when the user navigates from the RunningScreen to the ReadyScreen. I have been told I can do this using a route, but I have been having trouble properly setting it up. Here is what I have so far:

function RunningScreen({navigation, route}){

const checkFinish = () => {
     onPress: () => navigation.navigate('ReadyScreen, {
     didComeFromRunningScreen: true
 })
}

...

useFocusEffect(
   React.useCallback(()=>{
   ....
   if(didComeFromRunningScreen){
   toggleModal()
  }
  }, [])
}

I am also stuck on how to toggle this in the ReadyScreen

1 Answers

If you are going back to the previous screen you cant pass params like that. or if you forcefully push the previous screen to open again it will create a new stack. You have to pass a callback function from the ready screen to the running screen and in the running screen when your check the finish button press you will call your callback function.

Here is the code example:

ReadyScreen

const ReadyScreen = ({ navigation }) => {
  const toggleModal = () => {
    // Your modal method to open modal
  };

  // callback func
  const openModalCallBack = () => {
    toggleModal();
  };

  const gotoRunningScreen = () => {
    navigation.navigate("RunningScreen", { openModalCB: openModalCallBack }); // passing callback func
  };

  return (
    <View>
      <Button onPress={gotoRunningScreen} />
    </View>
  );
};
export default ReadyScreen;

RunningScreen

const RunningScreen = ({ navigation, route }) => {
  const checkFinish = () => {
    const { openModalCB } = route?.params;
    openModalCB(); // Here you calling the callback func
    navigation.goBack(); // or pop()
  };

  return (
    <View>
      <Button onPress={checkFinish} />
    </View>
  );
};
export default RunningScreen;
Related