Onjsdev

Share


Dimensions in react native

Dimensions in React Native | How To Handle Screen Orientation Changes


By onjsdev

Nov 6th, 2023

React Native is a popular framework for building mobile applications. It allows us to create apps for both iOS and Android platforms using a single codebase with Javascript. When developing mobile applications, it's crucial to understand and manage the dimensions of your app's user interface elements and adapt to various screen sizes and orientations.

In this article, we'll explore how to work with dimensions in React Native to ensure your app looks and functions consistently across different devices and orientations.

What are Dimensions?

Dimensions in React Native refer to the physical size of the user's device screen. These dimensions include width and height, and they play a vital role in designing responsive and user-friendly interfaces. React Native provides a Dimensions API that allows you to access the screen dimensions and adapt your app's layout and design accordingly.

Getting Screen Sizes In React Native

To retrieve the screen dimensions in React Native, you can use the Dimensions API as follows:

import { Dimensions } from 'react-native';

const { width, height } = Dimensions.get('window');

Here, Dimensions.get('window') provides you with the width and height of the device screen. You can use these values to adjust your UI components dynamically based on the available screen space.

How To Detect Screen Orientations

Screen orientation, whether in portrait or landscape mode, can significantly impact your app's design. React Native offers a straightforward approach to detect the current screen orientation using the Dimensions API.

import { Dimensions } from 'react-native';


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

const orientation = isPortrait() ? 'portrait' : 'landscape';

By checking the relative values of height and width, you can determine whether the device is in portrait or landscape mode. This information can help you make layout adjustments as needed.

Handling Orientation Changes

An user can prefer using application in different orientations so you must handle also orientation changes. This is also straightforward process. React Native provides an event listener to handle screen orientation changes. You can use the Dimensions.addEventListener method to subscribe to changes and update your UI accordingly:

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

function OrientationChangeExample() {
  const [orientation, setOrientation] = useState('portrait');

  useEffect(() => {
    const handleOrientationChange = ({ window }) => {
      const { width, height } = window;
      if (width > height) {
        setOrientation('landscape');
      } else {
        setOrientation('portrait');
      }
    };

    // Add an event listener to detect changes in screen dimensions (orientation changes)
    Dimensions.addEventListener('change', handleOrientationChange);

    // Initial orientation check
    handleOrientationChange(Dimensions.get('window'));

    // Remove the event listener when the component unmounts
    return () => {
      Dimensions.removeEventListener('change', handleOrientationChange);
    };
  }, []);

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Current Orientation: {orientation}</Text>
    </View>
  );
}

export default OrientationChangeExample;

In this component, we use the useState hook to manage the orientation state, and we use the useEffect hook to add and remove the event listener. When the screen dimensions change (e.g., on an orientation change), the handleOrientationChange function is called to update the orientation state based on the new dimensions.

Locking Screen in an Orientation

In some cases, you may want to lock your app to a specific orientation, preventing it from rotating when the user tilts their device. To achieve this, you can use the react-native-orientation-locker library, which provides a more robust way to manage screen orientations:

npm install react-native-orientation-locker

After installing the library, you can use it to lock your app in a particular orientation:

import Orientation from 'react-native-orientation-locker';
// Lock to portrait
Orientation.lockToPortrait();

// Lock to landscape
Orientation.lockToLandscape();

This approach gives you more control over your app's orientation behavior.

Orientation-Based Styling

In addition to handling screen dimensions and orientation changes, You may want to style your UI components based on the current screen orientation which is very useful when you want to fine-tune your app's appearance for portrait and landscape modes.

To achieve orientation-based styling, you can use conditional rendering of styles based on the detected orientation. Here's an example of how you can apply different styles for portrait and landscape orientations:

import React, { useState, useEffect } from 'react';
import { Dimensions, StyleSheet, Text, View } from 'react-native';

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

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  portraitText: {
    fontSize: 20,
    color: 'blue',
  },
  landscapeText: {
    fontSize: 24,
    color: 'green',
  },
});

function MyComponent() {
  const [orientation, setOrientation] = useState(isPortrait() ? 'portrait' : 'landscape');

  useEffect(() => {
    const onDimensionsChange = () => {
      setOrientation(isPortrait() ? 'portrait' : 'landscape');
    };

    Dimensions.addEventListener('change', onDimensionsChange);

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

  return (
    <View style={styles.container}>
      <Text style={orientation === 'portrait' ? styles.portraitText : styles.landscapeText}>
        Welcome to React Native Orientation Styling!
      </Text>
    </View>
  );
}

export default MyComponent;

Now, your component will respond to changes in screen orientation and update the styles accordingly.

Conclusion

Understanding and managing dimensions and screen orientation in React Native is crucial for delivering user-friendly mobile app experience. By using the React Native Dimensions API and a few logic you can build responsive applications with ease.

Thank you for reading.