Jerry Seigle
Jerry Seigle

Reputation: 457

React Native How to get orientation of device

The current code below will get the orientation however if the device is in Landscape view and you open the app it shows portrait view. After manual rotating the device it code below works correctly How do I get the orientation of the device when app starts. #React #React Native

const ViewControllerProvider = (props) => {
  const [orientation, setOrientation] = useState('PORTRAIT');

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

  return (
    <ViewControllerContext.Provider value={{orientation}}>
      {props.children}
    </ViewControllerContext.Provider>
  );
};

export {ViewControllerProvider, ViewControllerContext};

Upvotes: 1

Views: 9584

Answers (3)

Jakob Sch&#246;dl
Jakob Sch&#246;dl

Reputation: 406

Using the new useWindowDimensions hook:

import { useWindowDimensions } from 'react-native';

const {height, width} = useWindowDimensions();
const isLandscape = width > height;

Upvotes: 0

naveed ahmed
naveed ahmed

Reputation: 470

import { useDeviceOrientation } from '@react-native-community/hooks';

const App=()=>{
const orientation = useDeviceOrientation()
<View bottom: orientation.landscape==true?0:10>
</View>

Upvotes: 3

jnpdx
jnpdx

Reputation: 52337

When you add the listener, you can also do a manual call to get the initial orientation:

  const [orientation, setOrientation] = useState('LANDSCAPE');

  const determineAndSetOrientation = () => {
    let width = Dimensions.get('window').width;
    let height = Dimensions.get('window').height;

    if (width < height) {
        setOrientation('PORTRAIT');
      } else {
        setOrientation('LANDSCAPE');
      }
  }

  useEffect(() => {

    determineAndSetOrientation();
    Dimensions.addEventListener('change', determineAndSetOrientation);

    return () => {
      Dimensions.removeEventListener('change', determineAndSetOrientation)
    }
  }, []);

Also probably a good idea to remove the event listener (see the return statement).

Upvotes: 8

Related Questions