I am trying to a make a trigger whenever the user presses the back button from their phone to call a function (where the function will go back to the previous screen with the necessary parameters that I need for the app to work correctly), however either it is ignoring the function, or it's not passing it at all, and I can't figure out why.
I looked at these resources and they didn't help me in this particular case:
React Native - Device back button handling
https://reactnative.dev/docs/backhandler
This is part of the code I used, going back from the chat screen to the user's profile screen
import { BackHandler } from "react-native";
function handleBackButtonClick() {
props.navigation.navigate("MenuScreen", {
screen: "userProfileScreen",
params: {
accountId: managerId,
origin: "chatScreen"
}
});
return true;
}
useEffect(() => {
BackHandler.addEventListener("hardwareBackPress", handleBackButtonClick);
return () => {
BackHandler.removeEventListener("hardwareBackPress", handleBackButtonClick);
};
}, []);
When I call the function from an onPress, it works as intended
<TouchableOpacity style={{ height: 48, width: 48, justifyContent: "center" }}
onPress={() => handleBackButtonClick()}>
<Text>Clicking here works as intended</Text>
</TouchableOpacity>
Am I doing something fundamentally wrong with the handleBackButtonClick? How do I make it work?
Edit: For more information, it is built upon multiple stack navigators in the menu navigator, which you can see here:
const Stack = createNativeStackNavigator();
function MenuNavigator({ route }) {
return (
<Stack.Navigator screenOptions={() => ({ headerShown: false })}>
<Stack.Screen name="inDevelopmentScreen" component={InDevelopmentScreen} />
<Stack.Screen name="profileScreen" component={ProfileScreen} />
<Stack.Screen name="myScreen" component={MyScreen} />
<Stack.Screen name="userProfileScreen" component={UserProfileScreen}
listeners={({ navigation }) => ({
blur: () => {
navigation.setParams({ accountId: undefined })
}
})} />
<Stack.Screen name="otherScreen" component={OtherScreen} />
<Stack.Screen name="chatScreen" component={ChatScreen} />
/* Ect... */
</Stack.Navigator>
);
}