screen orientation on react native

Viewed 1712

I am trying to add the rotation functionality on react native using expo. Followed tutorials and searched on google and here but somehow none of them are working. The screen size is not getting detected when i rotate the simulator. Therefore it doesn't change from portrait to landscape or vice versa. You can see the code below that i tried through following a working example but its not working when i apply it. Any help is very much appreciated.

const [orientation, setOrientation] = useState("");
const window = useWindowDimensions();

 useEffect(() => {
  Dimensions.addEventListener("change", ({ window: { width, height } }) => {
   if (width < height) {
    // this is in portrait mode
    setOrientation("Portrait");
   } else {
    // this is in landscape mode
    setOrientation("Landscape");
   }
 });
}, []);

return (
  <View style={styles.container}>
   <Text style={{ color: "red", fontSize: 30, fontWeight: "bold" }}>
     {orientation}
   </Text>
  </View>

const styles = StyleSheet.create({
  container: {
  flex: 1,
  alignItems: "center",
  justifyContent: "center",
 },
});
1 Answers

I have a very clean and efficient way to solve this

Working Example

Create a folder called components and inside that create a file called Orientation.js

Then inside Orientation.js

import { Dimensions } from 'react-native';

const msp = (dim, limit) => {
  return dim.scale * dim.width >= limit || dim.scale * dim.height >= limit;
};

const isPortrait = () => {
  const dim = Dimensions.get('screen');
  return dim.height >= dim.width;
};

const isLandscape = () => {
  const dim = Dimensions.get('screen');
  return dim.width >= dim.height;
};

const isTablet = () => {
  const dim = Dimensions.get('screen');
  return (
    (dim.scale < 2 && msp(dim, 1000)) || (dim.scale >= 2 && msp(dim, 1900))
  );
};

const isPhone = () => {
  return !isTablet();
};

export default {
  isPortrait,
  isLandscape,
  isTablet,
  isPhone,
};

Then set your state and useEffect like this

import Orientation from "./components/Orientation"

const [orientation, setOrientation] = useState(
    Orientation.isPortrait() ? 'portrait' : 'landscape'
  );

  useEffect(() => {
    Dimensions.addEventListener('change', () => {
      setOrientation(Orientation.isPortrait() ? 'portrait' : 'landscape');
    });
  }, []);

This will work perfectly as you require

Results :

Portrait Result

Landscape Result

Related