Search code examples
react-nativereact-navigationgesture

How to disable screen gestures using react-navigation@3.x


Original Problem

NOTE: This is only for react-navigation@3.x

We wanted to disable the "swipe to go back" functionality for a specific screen based on some conditional parameters. While this is easily accomplished when instantiating the screen in the StackNavigator, we struggled to find any documentation or references on how to handle this dynamically.

This was also compounded by the fact that react-navigation is on version 6.x and they have renamed the specific parameter numerous times, while we are still using version 3.x. Hope this helps someone as it took me longer than I would like to admit to get this working.

Additional Information

In react-navigation@6.x they renamed gesturesEnabled to gestureEnabled


Solution

  • Disabling Screen Gestures

    This is for react-navigation@3.x here are a few options (note that for the conditional examples the param name can be anything). This is the navigation option which controls swipe to go back functionality:

    gesturesEnabled: boolean // defaults to true
    

    Functional Components (Static)

    MyScreen.navigationOptions = {
      gesturesEnabled: false
    }
    

    Functional Component (Conditional)

    MyScreen.navigationOptions = ({ navigation }) => ({
       gesturesEnabled: navigation.getParam('myCondition', true) // second param is default value
    })
    

    Class Components (Static)

    class MyScreen extends React.Component {
    
      static navigationOptions = {
        gesturesEnabled: false
      }
    
      render() {
        // ...
      }
    }
    

    Class Components (Conditional)

    class MyScreen extends React.Component {
    
      static navigationOptions = ({ navigation }) => ({
        gesturesEnabled: navigation.getParam('isGestureEnabled', true),
      })
    
      disableScreenGestures() {
        this.props.navigation.setParams({ isGestureEnabled: false })
      }
    
      enableScreenGestures() {
        this.props.navigation.setParams({ isGestureEnabled: true })
      }
    
      render() {
        return (
          <Button onPress={() => this.disableScreenGestures()} />
        )
      }
    }