typescriptreact-nativerotationscreen-rotation

How to unlock rotation on one screen in react native


I tried using react-native-orientation in a webview to get it being the only view that would rotate.

import React, {useEffect} from 'react';
import { WebView } from 'react-native-webview';
import Orientation from "react-native-orientation"

export function GameWebViewScreen({navigation}) {
const link = ****

useEffect(() => {
    Orientation.unlockAllOrientations();
}, [])

return <WebView source={{uri: link}}/>
}

I am getting TypeError: null in not an object on unlockAllOrientations call. Does anyone know is this a problem because I haven't configured the native files as it says in instructions here since I don't have the access to them yet or?

I also tried with class component and got the same result.

I am also open for any other suggestions on libraries for controlling rotation on single views.


Solution

  • You need to set native files as per instructions and Try to do manual linking.

    Listen to device orientation changes in React Native applications and programmatically set preferred orientation on a per screen basis. Works on both Android and iOS.

    Example:-

    import Orientation from 'react-native-orientation'
    
    componentDidMount() {
       Orientation.unlockAllOrientations();
    }
    
    componentWillUnmount() {
       Orientation.lockToPortrait();
    }
    

    You need to set app delegate as follow in ios

    #import "Orientation.h"
    
    - (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
      return [Orientation getOrientation];
    }
    

    Android need to set Orientation Package

    Implement onConfigurationChanged method in MainActivity.java

    import android.content.Intent; // <--- import 
    import android.content.res.Configuration; // <--- import 
    
    public class MainActivity extends ReactActivity {
      @Override
      public void onConfigurationChanged(Configuration newConfig) {
         super.onConfigurationChanged(newConfig);
         Intent intent = new Intent("onConfigurationChanged");
         intent.putExtra("newConfig", newConfig);
         this.sendBroadcast(intent);
      }
    }
    

    You can find more information here react-native-orientation