skip to Main Content

I am use react-native 0.70.6, and use Drawer navigation @react-navigation/drawer: "^6.5.6" for the navigate.
When I press device back button i want to redirect previous menu(screen) but right now it’s close the app.

When I use navigation.goBack() in my about.js file it’s work properly but when i press device back button it’s close the app.

Here is my code

In my App.js file

import MyDrawer from './sidemenubar';

<View style={{ flex: 1 }}>
  <NavigationContainer>
    <Stack.Navigator
      initialRouteName="Splash"
      screenOptions={{
        headerShown: false,
        orientation: 'portrait'
      }}
    >
      <Stack.Screen name="Sidemenubar" component={MyDrawer} /> //for custom drawer 
      <Stack.Screen name="Splash" component={Splash} />
    </Stack.Navigator>
  </NavigationContainer>
  <AlertDialog />
</View>

In my sidemenubar.js file

import { createDrawerNavigator } from '@react-navigation/drawer';
const Drawer = createDrawerNavigator();
    
<Drawer.Navigator
    drawerContent={props => <CustomDrawer {...props} />}
    useLegacyImplementation={true}
    initialRouteName="Dashboard">
          <Drawer.Screen
            name="Dashboard"
            component={Dashboard}
          />
           <Drawer.Screen
            name="About"
            component={About}       
          />      
    </Drawer.Navigator>

How can i fix this issue Please help me…
Thanks.

2

Answers


  1. You have to use the BackHandler from react-native.

    Just register the hardwareBackPress event on mounting the component and don’t forget to remove it while onmounting:

        componentWillMount() {
            BackHandler.addEventListener('hardwareBackPress', this.props.navigation.goBack());
        }
        
        componentWillUnmount() {
            BackHandler.removeEventListener('hardwareBackPress',true);
        }
    

    That should hopefully solve your issue.

    Login or Signup to reply.
  2. For functional component.

    import { BackHandler } from 'react-native';
    
    function handleBackButtonClick() {
        navigation.goBack();
        return true;
      }
    
      useEffect(() => {
        BackHandler.addEventListener('hardwareBackPress', handleBackButtonClick);
        return () => {
          BackHandler.removeEventListener('hardwareBackPress', handleBackButtonClick);
        };
      }, []);
    

    You can try using useBackHandler hook.

    import { useBackHandler } from '@react-native-community/hooks'
    
    useBackHandler(() => {
      if (shouldBeHandledHere) {
        // handle it
        return true
      }
      // let the default thing happen
      return false
    })
    

    Let me know does this helps you or not.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search