Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle locked orientation using React Native Stack Navigation

I've an React Native Expo app running on both iOS and Android using Stack Navigation with two views. The first view is locked to portrait screen orientation

export class HomeScreen extends Component {
  componentWillMount() {
    ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.PORTRAIT_UP);
  }

  render() {...
  }
}

The second view should be available in both portrait and landscape screen orientation:

export class DetailScreen extends Component {
  componentDidMount() {
    ScreenOrientation.lockAsync(
      ScreenOrientation.OrientationLock.ALL_BUT_UPSIDE_DOWN
    );
  }

  async componentWillUnmount() {
    await ScreenOrientation.lockAsync(
      ScreenOrientation.OrientationLock.PORTRAIT_UP
    );
  }

  render() {...
  }
}

This is working almost as expected, but I have two issues:

  1. When second view (DetailScreen) is in landscape and the back button is pressed, the first view (HomeScreen) is briefly shown in landscape orientation before rotation back to the portrait orientation. Is it possible to ensure that the device has rotated to portrait before navigating back? I tried doing that using async await in the componentWillUnmount method inside the DetailScreen, but the screen is still in landscape when the component is unmounted.

HomeSceen is briefly shown in landscape orientation

  1. Using gestures I'm able to navigate back to the HomeScreen. But doing this gesture when the DetailScreen is shown in landscape, the HomeScreen is shown in landscape as well. How can I handle this? Is it possible somehow to disable this gesture inside the DetailScreen when in landscape orientation?

enter image description here

The example is available in this Expo Snack: https://snack.expo.io/HJ_nhkQKH

like image 991
dhrm Avatar asked Mar 26 '26 19:03

dhrm


1 Answers

I updated the expo snack for your question: https://snack.expo.io/BJfXseXYB

Part 1. using NavigationEvents - onWillFocus

Part 2:

const RootStack = createStackNavigator(

  {
    Home: {
      screen: HomeScreen,
      navigationOptions: {
        gesturesEnabled: true,
      },
    },

    DetailView: {
      screen: DetailScreen,
      navigationOptions: {
        gesturesEnabled: false,
      },
    },
  },

  {
    initialRouteName: 'Home',
  }
);
like image 78
Oleg Avatar answered Mar 29 '26 12:03

Oleg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!