Why when I try to use react native hooks it does not work properly as intended to be?

Viewed 914

I am developing an app using react native, when I try to console.log(useDeviceOrientation());. The output (true/false) during the portrait and landscape did not change. Could someone help?

The library that is used is: @react-native-community/hooks

API that I used: useDeviceOrientation

What I try to do:

  1. uninstall the library
  2. reinstall the same library
  3. add dependencies of the library to package.json
  4. same problem occurred. no changes when changing orientation

Code:

// import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { Dimensions, StyleSheet, SafeAreaView, Alert, Button, Platform, StatusBar, View } from 'react-native';
import { useDimensions, useDeviceOrientation } from '@react-native-community/hooks'

export default function App() {
  console.log(useDeviceOrientation());
  const { landscape } = useDeviceOrientation();

  return (
    <SafeAreaView style={styles.container}>
      <View style={{
        backgroundColor: "dodgerblue",
        width: "100%",
        height: landscape ? "100%" : "30%",
      }}
      ></View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    paddingTop: Platform.OS === "android" ? StatusBar.currentHeight : 0,
    // justifyContent: "center",
    // alignItems: "center",
  },
});
4 Answers

There is no need of 3rd party library for this. You can simply use this approach. First create a functional component named useOrientarion,

import { useWindowDimensions } from 'react-native';

const useOrientation = () => {
  const height = useWindowDimensions().height;
  const width = useWindowDimensions().width;

  return { isPortrait: height > width };
};

export default useOrientation;

and then in your component,

// import useOrientation
import useOrientation from './useOrientation';

function App() {
  const orientation = useOrientation();
  console.log(orientation);
  // use orientation wherever you want
  // OUTPUT:  {"isPortrait": true} or  {"isPortrait": false}
}

it works for me.

const { height, width } = useDimensions().window;
const landscape = width > height;

react-native-community

I had the same issue; stopping the app and re-building was sufficient to have it fixed.

Related