Home > front end >  Pass params to previous screen on swipe/gesture
Pass params to previous screen on swipe/gesture

Time:05-03

I've thoroughly read the documentation on passing params between screens with React Navigation: https://reactnavigation.org/docs/params/

However, all of those examples only work if you are calling navigation.navigate manually and passing the params. For example:

<Button
  title="Done"
  onPress={() => {
    // Pass and merge params back to home screen
    navigation.navigate({
     name: 'Home',
     params: { post: postText },
     merge: true,
    });
  }}
/>

I have a screen with a back button, where I can call navigation.navigate and pass params on button press, like in the example above. However, the user can also swipe from the left to go back to the first screen on Android (and I'm assuming iOS as well).

So, my question:

Is there a way for me to pass the same data to the previous screen when the user swipes to go back (instead of pressing the back button)?

CodePudding user response:

There might be a better way that I am unaware of. However, we can achieve this manually by preventing the default back action and handling this ourselves.

Suppose that you have a screen B and you want to swipe back to go to a screen Home and pass params to Home from B on that swipe action. Then, you can achieve this as follows.

function B({navigation}) {

  React.useEffect(() => navigation.addListener('beforeRemove', (e) => {
         
        // the navigation.navigate will fire beforeRemove which causes an infinite loop. we guard this here
        if (e.data.action.type === "NAVIGATE") {
          return
        }
        // Prevent default behavior of leaving the screen
        e.preventDefault();
        
        // navigate manually
        navigation.navigate({
            name: 'Home',
            params: { post: postText },
            merge: true,
        });        
        
   }), [navigation]);

  return ( ... )
}

Edit: The navigation.navigate fires the beforeRemove event again, obviously, which causes an infinite loop. We can guard this as shown above.

  • Related