Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native, Detect screen rotation change using portrait mode

I am using portrait mode in react-native application. But I want to capture the rotation event of the screen. Is there a way to do this?

Thanks...

like image 432
Sinan Coskun Avatar asked Jun 19 '20 14:06

Sinan Coskun


People also ask

How do you handle screen orientation changes in react native?

For Android, open the AndroidManifest. xml file and within the activity element add 'android:screenOrientation="portrait"' to lock to portrait or 'android:screenOrientation="landscape"' to lock to landscape.

How does react native detect device orientation?

on iOS you need to allow your app to rotate. In XCode you need to go to target and then in the Deployment Info -> Device Orientation enable the orientaitons your app should support. For android you'll have to modify your AndroidManifest file and set the screenOrientation on the activity tag.


1 Answers

this function might help you
create a useOrientation.js file

import {useEffect, useState} from 'react';
import {Dimensions} from 'react-native';

export function useOrientation(){
  const [orientation, setOrientation] = useState("PORTRAIT");

  useEffect(() => {
    Dimensions.addEventListener('change', ({window:{width,height}})=>{
      if (width<height) {
        setOrientation("PORTRAIT")
      } else {
        setOrientation("LANDSCAPE")
    
      }
    })

  }, []);

  return orientation;
}
like image 127
shammi Avatar answered Sep 30 '22 02:09

shammi