How to prevent rotation of the screen with React native?

Estimated read time 2 min read

To prevent rotation of the screen with React Native, you can use the react-native-orientation-locker library. This library provides a simple API for locking the screen orientation to a specific orientation.

Here’s an example code snippet that demonstrates how to prevent rotation of the screen with React Native:

  1. Install the react-native-orientation-locker library using npm:
npm install react-native-orientation-locker --save
  1. Import the react-native-orientation-locker library in your code:
import Orientation from 'react-native-orientation-locker';
  1. Call the lockToPortrait method to lock the screen orientation to portrait mode:
import React, { useEffect } from 'react';
import { View } from 'react-native';
import Orientation from 'react-native-orientation-locker';

function MyComponent() {
  useEffect(() => {
    Orientation.lockToPortrait();
    return () => {
      Orientation.unlockAllOrientations();
    };
  }, []);

  return (
    <View>
      {/* Your component's UI here */}
    </View>
  );
}

export default MyComponent;

In this example, we define a functional component named “MyComponent” that uses the useEffect hook to lock the screen orientation to portrait mode when the component is mounted. We use the lockToPortrait method from the react-native-orientation-locker library to lock the screen orientation to portrait mode.

We also use the unlockAllOrientations method to unlock the screen orientation when the component is unmounted.

In the JSX code, we display the component’s UI.

By using the react-native-orientation-locker library, we can prevent rotation of the screen with React Native.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply