React Native, Detect screen rotation change using portrait mode
Solution 1
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;
}
Solution 2
To complete the previous answers,
if you simply want your app to be responsive, it is easier to use useWindowDimensions()
https://reactnative.dev/docs/usewindowdimensions
Just put something like this in your root component :
const SCREEN_WIDTH = useWindowDimensions().width;
const SCREEN_HEIGHT = useWindowDimensions().height;
return (
<View style={{ width: SCREEN_WIDTH, minHeight: SCREEN_HEIGHT}} >
//the rest of your app
</View>
);
Solution 3
Well, you have several options. You can use the Dimensions API https://reactnative.dev/docs/dimensions
You can add a listener for Dimensions.change and you could do something like
function isPortrait() {
const dim = Dimension.get("screen")
return dim.height >= dim.width
}
function isLandscape() {
const dim = Dimension.get("screen")
return dim.width >= dim.height
}
now add listen to dimension chagnes with
Dimensions.addEventListener("change", () => {
// orientation has changed, check if it is portrait or landscape here
})
Another posibility is to use the one of the orientation packages available such as https://github.com/wonday/react-native-orientation-locker
Solution 4
useDeviceOrientation: will return an object which will be updated each time the device will change the orientation "true or false"
import { useDeviceOrientation } from "@react-native-community/hooks";
Example object returned by useDeviceOrientation
:
{
"landscape": false,
"portrait": true,
}
We can destructure the object:
const { landscape } = useDeviceOrientation();
Than we can use it :
height: landscape ? "100%" : "30%"
Sinan Coskun
Updated on June 16, 2022Comments
-
Sinan Coskun almost 2 years
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...