Logo

dev-resources.site

for different kinds of informations.

Mobile Orientation (React-Native)

Published at
9/17/2024
Categories
customhooks
react
reactnative
orienation
Author
vaibhav_shukla_newsletter
Author
25 person written this
vaibhav_shukla_newsletter
open
Mobile Orientation (React-Native)

Lets dive straight into code

To create custom hooks that listens to device orientation we will be using Dimensions API to Detect changes in screen.

Image description


import { useState, useEffect } from 'react';
import { Dimensions } from 'react-native';

const useOrientation = () => {
  const [orientation, setOrientation] = useState(getOrientation());

  // Function to determine the current orientation
  function getOrientation() {
    const { width, height } = Dimensions.get('window');
    return width > height ? 'LANDSCAPE' : 'PORTRAIT';
  }

  useEffect(() => {
    const onChange = () => {
      setOrientation(getOrientation());
    };

    // Listen for changes in screen dimensions
    const subscription = Dimensions.addEventListener('change', onChange);

    // Cleanup the event listener when the component is unmounted
    return () => {
      subscription.remove();
    };
  }, []);

  return orientation;
};

export default useOrientation;

Enter fullscreen mode Exit fullscreen mode
customhooks Article's
29 articles in total
Favicon
Mastering Navigation Control in React with useCallbackPrompt and useBlocker 🚦
Favicon
Custom Hooks in React: Reusing Logic Across Components
Favicon
Fixing UI Update Issues with Custom Hooks in React
Favicon
Custom Hooks in React: A Guide to Creation and Usage
Favicon
React: leveraging custom hooks to extract reusable logic
Favicon
Custom Hooks
Favicon
Custom Hooks in React
Favicon
Mobile Orientation (React-Native)
Favicon
Reusing Logic in React with Custom Hooks: a Practical guide
Favicon
Harnessing Firebase in React with Custom Hooks: A Practical Guide
Favicon
Building Powerful React Components with Custom Hooks
Favicon
React Custom Hooks (useNetworkStatus)
Favicon
React Custom Hooks (useMediaPermission)
Favicon
React Custom Hooks (useDebounce)
Favicon
How to Create a Counter App with useReducer and Custom Hooks
Favicon
How to create custom Hooks in React.Js?
Favicon
React Slideshow Component with autoplay, fullscreen mode and expand all
Favicon
React Portals: create and open modals with keyboard keys
Favicon
Learn Something on React JSX and Hooks
Favicon
How to create Tabs in ReactJs using Hooks ?
Favicon
Simple hook to handle featue flags
Favicon
React custom hooks to update form data
Favicon
useIpAdrress()
Favicon
Custom hook useScroll.tsx :: React TypeScript
Favicon
useQuery() with React Router Dom
Favicon
React Custom Hooks
Favicon
useGeoPosition Hook - A Custom React Hook to grab latitude and longitude from a given address.
Favicon
`useBackButton` hook to handle back button behavior in React Native
Favicon
Form in Modal using React hooks – mistakes and lesson learnt

Featured ones: