Disable back button in a specific Screen (React Navigation Stack)
Asked Answered
G

1

6

Hello!

I need to disable the back button on the navigation bar. help me plsss.

Routes

  • Home: I don't want to leave the application
  • Success: I don't want to go back to Checkout.

Example: click here

import React from 'react';
import { createStackNavigator } from '@react-navigation/stack';
import { OrderProvider } from '../contexts/order';

import Home from '../pages/Home';
import Checkout from '../pages/Checkout';
import Success from '../pages/Checkout/success';

const AppStack = createStackNavigator();

const AppRoutes = () => (
  <OrderProvider>
    <AppStack.Navigator screenOptions={{ headerShown: false }}> 
      <AppStack.Screen name="Home" component={Home} />  <-- here
      <AppStack.Screen name="Checkout" component={Checkout} />
      <AppStack.Screen name="Success" component={Success} /> <--- here
    </AppStack.Navigator>
  </OrderProvider>
);

export default AppRoutes;

import React from 'react';
import { View} from 'react-native';

const Success = () => {
  return (
    <View />
  );
};

export default Success;
Glottology answered 13/7, 2020 at 18:29 Comment(0)
M
9

You can do the following:

const Home = () => {
  useFocusEffect(
    React.useCallback(() => {
      const onBackPress = () => {
        return true;
      };

      BackHandler.addEventListener('hardwareBackPress', onBackPress);

      return () =>
        BackHandler.removeEventListener('hardwareBackPress', onBackPress);
    }, []),
  );
  // ...
};
const Success = ({navigation}) => {
  useFocusEffect(
    React.useCallback(() => {
      const onBackPress = () => {
        navigation.navigate('Home');
        return true;
      };

      BackHandler.addEventListener('hardwareBackPress', onBackPress);

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

I've set it up so that clicking back on the Home screen does nothing by returning true when the hardwareBackPress event is called.

For the Success screen I navigate back to Home.

I assumed this is the behavior you're looking for from reading your question.


It is important that you don't forget to import useFocusEffect from react-navigation everywhere you use it:

import { useFocusEffect } from '@react-navigation/native';

When to return true or false in the hardwareBackPress event handler function is explained in the react navigation documentation:

Returning true from onBackPress denotes that we have handled the event, and react-navigation's listener will not get called, thus not popping the screen. Returning false will cause the event to bubble up and react-navigation's listener will pop the screen.

If you want to read more read the documentation here: https://reactnavigation.org/docs/custom-android-back-button-handling/.

Menton answered 13/7, 2020 at 19:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.