Reputation: 546
I'm using React Navigation in a react-native app. So I followed the docs at https://reactnavigation.org/docs/custom-android-back-button-handling/ to implement Custom Android back button behavior using this snippet.
Screen One.js
import React, {useCallback} from 'react';
import {useFocusEffect} from '@react-navigation/native';
import {
View,
Text,
BackHandler,
} from 'react-native';
export function ScreenOne({navigation}) {
useFocusEffect(
useCallback(() => {
const onBackPress = () => {
if (isSelectionModeEnabled()) {
disableSelectionMode();
return true;
} else {
return false;
}
};
BackHandler.addEventListener('hardwareBackPress', onBackPress);
return () =>
BackHandler.removeEventListener('hardwareBackPress', onBackPress);
}, [isSelectionModeEnabled, disableSelectionMode])
);
return (
<View>
<Text>Demo</Text>
</View>
)
}
Stack.js
import React from 'react';
import {createStackNavigator, HeaderBackButton} from '@react-navigation/stack';
import {
ScreenOne,
ScreenTwo,
} from '../screens';
const Stack = createStackNavigator();
function AppStack() {
return (
<Stack.Navigator>
<Stack.Screen
name="ScreenTwo"
component={ScreenTwo}
options={{headerShown: false}}
/>
<Stack.Screen
name="ScreenOne"
component={ScreenOne}
options={({navigation}) => ({
headerShown: true,
headerLeft: () => (
<HeaderBackButton
onPress={() => {
navigation.replace('ScreenTwo');
}}
/>
),
})}
/>
</Stack.Navigator>
);
}
export default AppStack;
RootNavigation.js
import {createRef} from 'react';
export const isReadyRef = createRef();
export const navigationRef = createRef();
export function navigate(name, params) {
navigationRef.current?.navigate(name, params);
}
export function goBack() {
navigationRef.current?.goBack();
}
App.js
import 'react-native-gesture-handler';
import React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import Stack from './navigators/Stack';
import {navigationRef} from './navigators/RootNavigation';
import {AuthContext} from './context';
const App = () => {
return (
<AuthContext.Provider>
<NavigationContainer ref={navigationRef}>
<Stack />
</NavigationContainer>
</AuthContext.Provider>
);
};
export default App;
When I press the app back button, I keep getting this error:
ReferenceError: Can't find variable: isSelectionModeEnabled
Upvotes: 1
Views: 1073
Reputation: 183
isSelectionModeEnabled
and disableSelectionMode
is just an example. Similar to "if Modal is open, close it instead of navigating back, otherwise keep the default back button behaviour".
You do not need it and you should instead implement your own logic for your own use case and return true
to prevent the default navigation! Returning false
will keep the default back button behaviour.
If you just want to prevent the back button in any case, just do this:
const onBackPress = () => {
return true;
};
Here the relevant documentation: https://reactnative.dev/docs/backhandler
Upvotes: 6