javascriptreactjsreact-native

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};

Solution

  • 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).