Categories
JavaScript Answers React Native Answers

How to apply different styles applied on orientation change with React Native?

Spread the love

Sometimes, we want to apply different styles applied on orientation change with React Native.

In this article, we’ll look at how to apply different styles applied on orientation change with React Native.

How to apply different styles applied on orientation change with React Native?

To apply different styles applied on orientation change with React Native, we can call Dimension.addEventListener and the Platform.isPortrait methods.

For instance, we write:

import * as React from 'react';
import { View, Text, Dimensions, Platform } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';

export default function App() {
  React.useEffect(() => {
    const onDimensionChange = () => {
      console.log(Platform.isPortrait());
    };

    Dimensions.addEventListener('change', onDimensionChange);
    return () => {
      Dimensions.removeEventListener('change', onDimensionChange);
    };
  }, []);
  
  return <View></View>;
}

to call Dimensions.addEventListener method with 'change' to watch for changes in the screen dimensions.

onDimensionChange is the screen dimension change listener.

Platform.isPortrait returns true is our screen is in portrait mode.

We return a function that calls Dimensions.removeEventListener to remove the listener when App unmounts.

Conclusion

To apply different styles applied on orientation change with React Native, we can call Dimension.addEventListener and the Platform.isPortrait methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *