Issue
I am trying to change default android hardware back button behavior with react navigation. I have bottom tab navigator with 6 tabs. eg Tab1 to Tab6 . When i open app from notification (depending on some condition) the initial tabs are Tab5 or Tab6, but when i press android hardware back button i got switched to Tab1 (which is my Home tab) but i want to be switched to Tab4.
I managed to change back button behavior to open some modal and on button to navigate to tab 4. My question is , can that be done without some alerts or modal ?
as per documentation i wraped event listener in useFocusEffect and UseCallback
const jumpToMessage = TabActions.jumpTo('Message');
useFocusEffect(
useCallback(() => {
const backAction = () => {
navigation.dispatch(jumpToMessage);
};
const subscription = BackHandler.addEventListener(
'hardwareBackPress',
backAction
);
return subscription.remove();
}, [])
);
Solution
Use none
for backBehavior in Navigator to remove default handling and then use BackHandler
for custom behaviour. Below is the simple example which navigates to the previous tab.
const tabs = ['Tab 1', 'Tab 2', 'Tab 3', 'Tab 4', 'Tab 5'];
function Tabs() {
const navigation = useNavigation();
const state = useNavigationState((state) => state);
useEffect(() => {
const backAction = () => {
if (state != undefined) {
navigation.navigate(tabs[state.index > 0 ? state.index - 1 : 0]);
}
return true;
};
const backHandler = BackHandler.addEventListener(
'hardwareBackPress',
backAction
);
return () => backHandler.remove();
}, [navigation, state]);
return (
<Tab.Navigator backBehavior="none">
{tabs.map((tab) => (
<Tab.Screen name={tab} component={Screen} />
))}
</Tab.Navigator>
);
}
Answered By - user18309290
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.