Kerry
Kerry

Reputation: 454

How to make backhandler in react-native go back to home screen rather than exit app?

in the official doc for backhandler in react native, backhandler used for quitting the app.

here is the doc

useEffect(() => {
    const backAction = () => {
      Alert.alert("Hold on!", "Are you sure you want to go back?", [
        {
          text: "Cancel",
          onPress: () => null,
          style: "cancel"
        },
        { text: "YES", onPress: () => BackHandler.exitApp() }
      ]);
      return true;
    };

    const backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      backAction
    );

    return () => backHandler.remove();
  }, []);

What I want to do is I want to simplify it and rather than quitting the app I want to navigate it to the homepage when hitting physical back button(backhandler)

So here is the code

const CheckOutOrderReceipt = ({navigation, route}) => {
  const {OrderId} = route.params;

  useEffect(() => {
    const backAction = () => {
      BackHandler.navigation.reset({
        index: 0,
        routes: [{name: 'Home'}],
      });
            return true
    };
    const backHandler = BackHandler.addEventListener(
      'hardwareBackPress',
      backAction,
    );
    return () => backHandler.remove();
  }, []);

But when ever is press the back button. I got this error

undefined is not an object (evaluating '_reactNative.BackHandler.navigation.reset')

What am I doing wrong. Some one please suggest

Upvotes: 0

Views: 3902

Answers (2)

Horst
Horst

Reputation: 1739

BackHandler is responsible for Android's back button only. So it have no navigation related stuff.

You can simply use the navigation prop

import { CommonActions } from '@react-navigation/native';
...
const backAction = () => {
navigation.dispatch(
  CommonActions.reset({
     index: 0,
     routes: [{name: 'Home'}],
  })
);
}

And we don't want to get the listener mess, we would use useFocusEffect instead of useEffect

Together we have sth like:


const CheckOutOrderReceipt = ({ navigation, route }) => {
  const { OrderId } = route.params

  useFocusEffect(
    React.useCallback(() => {
      const onBackPress = () => {
        Alert.alert('Hold on!', 'Are you sure you want to exit app?', [
          {
            text: 'Cancel',
            onPress: () => null,
            style: 'cancel'
          },
          {
            text: 'YES',
            onPress: () => {
              navigation.dispatch(
                CommonActions.reset({
                  index: 0,
                  routes: [{ name: 'Home' }]
                })
              )
            }
          }
        ])
      }

      BackHandler.addEventListener('hardwareBackPress', onBackPress)

      return () =>
        BackHandler.removeEventListener('hardwareBackPress', onBackPress)
    }, [])
  )
}

Upvotes: 1

shammi
shammi

Reputation: 1409

you need to add this code in your home screen

import { BackHandler } from 'react-native'

useEffect(() => {
    BackHandler.addEventListener('hardwareBackPress', backAction);

    return () =>
        BackHandler.removeEventListener('hardwareBackPress', backAction);
}, []);

  const backAction = () => {
    if (navigation.isFocused()) {
        Alert.alert('Hold on!', 'Are you sure you want to exit app?', [
           {
               text: 'Cancel',
                onPress: () => null,
                style: 'cancel',
            },
           { text: 'YES', onPress: () => BackHandler.exitApp() },
        ]);
        return true;
    }
};

Upvotes: 0

Related Questions