React Native – How To Create Responsive Layouts In React Native ?

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn how to create Responsive Layouts in React Native. Native application developers put a lot of effort into making engaging and stable apps that are supported on multiple devices. This means that Android developers have to make sure that their apps are supported on hundreds of devices. iOS developers also need to support their apps on a growing number of devices.

React Native enables developers to develop apps that can run both on iOS and Android. The problem is that the number of devices they need to support now is doubled. One particular problem is making the app responsive. There is no such thing as CSS media queries in React Native. React Native developers need to scale all of their layouts to make the app responsive on smartphones, tablets, and other devices.

A famous quote about learning is :

” I am always ready to learn although I do not always like being taught. “

How To Create Responsive Layouts In React Native ?


So Let’s begin.


Problems With Responsive Layout in React Native

React Native developers make their apps work on one-dimensional devices as a default. As a result, the app looks distorted on devices with different dimensions because different devices have different pixel ratios. React Native style properties accept either Density-Independent Pixels (DP) or percentage.


Independent Pixels

A density-independent pixel is a unit of length that enables mobile apps to scale across different screen sizes. DPs are not the classic screen pixels. Rather, DPs are mathematically calculated through the following equation: DP=PX/ScaleFactor.

PX is the number of classic screen pixels, and the scaling factor indicates how much the pixels should be enlarged.

React Native developers can scale DP values to screens of different sizes only if they have the same resolution. The problem is that there are hundreds of different devices and most of them have screens with different resolutions.


Percentage

Most web development frameworks use percentage values to design different layouts. However, React Native style properties like border-radius and border-width do not accept percentage value. Properties that do accept percentage include maxWidthminWidthmargin and height.


Useful Tips for Creating Responsive Layouts for React Native Apps

The following tips will help us develop responsive React Native apps on a massive range of devices.


1. Layout With Flexbox

Components can control layout with a flexbox algorithm. It’s created to keep the proportions and consistency of the layout on different screen sizes.

Flexbox works very similar to CSS on the Web with just a few exceptions which are really easy to learn. When flex prop is a positive number, then components become flexible and will adjust to the screen respective to its flex value. That means that flex equates to flexGrow: [number], flexShrink: 1, flexBasis: 0.

When flex: 0 — it’s sized accordingly to the height and width and is inflexible. If flex is a negative number it also uses height and width but if there is not enough space it will shrink to its minHeight and minWidth.

There are few main properties provided by flexbox, so let’s get through them!

Flex – describes how elements divide space between them. As mentioned above it’s limited to single numbers. If all elements have flex: 1 they will have the same width. In other cases they will split the sum of the flex among themselves.

Image1: Flexbox Properties : flex
Image1: Flexbox Properties : flex
Image2 : Flexbox Properties : flex
Image2 : Flexbox Properties : flex

Flex direction – controls the direction or the main axis of the content layout. You can layout the content in a row or in a column. The default direction is a column because of the nature of mobile device screens.

Justify content – describes the position of content along the main axis. You can align the content to the right-left of the center of the main axis. You can also determine the space between content components.

Image1 : Flexbox Properties : justifyContent : space-between
Image1 : Flexbox Properties : justifyContent : space-between
Image2 : Flexbox Properties : justifyContent : space-around
Image2 : Flexbox Properties : justifyContent : space-around
Image3 : Flexbox Properties : justifyContent : center
Image3 : Flexbox Properties : justifyContent : center

Align items – aligns content on the cross axis, as opposed to justifyContent that aligns on the main axis.

Flex prop do a really good job of keeping proportions between elements. Regardless of screen size. FlexDirection and justifyContent keep layout behaviour consistent.

There are many more flexbox props. We touched just a few to show how they can be helpful.


2. Aspect Ratio

Another cool prop is aspect ratio which helps keep proportions of our elements under control. Aspect ratio describes the relationship between the width and the height of an image. Aspect ratio is usually expressed as two numbers separated by a colon, like 16:9. Aspect ratio is a non-standard property available only in React Native, and not in CSS. The aspect ratio property controls the size of undefined element dimensions.

For example, we can use the aspectRatio property to adjust images to screen size when our images extend beyond the screen dimensions. We do not need to know the actual width and height of the image, just set the aspect ratio to 1:1. Our images will take all available screen width, without extending beyond the dimensions.


3. Screen Dimensions

It is great when our designs are the same for both platforms, and all types of devices (mobile, tablets, ipads). However, sometimes we have to deal with different layouts for specific screen dimensions or device types.

React Native does not provide properties that can identify the device type or screen size when we work with different layouts. The solution is to use the Dimensions API. The syntax for obtaining the dimensions of a screen is:

import { Dimensions } from 'react-native';

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

Since React Native 0.61 we can also use a hook.

const {width, height} = useWindowDimensions();

Once we obtain the width from supported range screen sizes , we can pick breakpoints from which our layout can change. We can provide different styles to component or hide some parts of the screen. This is similar behaviour to media queries used in CSS.

import { Text, View, Dimensions } from 'react-native';
 
class App extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      width: Dimensions.get('window').width
    };
  }
 
  render() {
    return (
     <View>
       {this.state.width < 320 ? <Text>width of the past</Text> : <Text>how big is big enough?</Text>}
     </View>
    );
  }
}


4. Detect the Platform

Apart from screen size we can also change the layout depending on which platform app is launched. To achieve this , we can use the Platform module.

There are many cases where it can be used:

In component render function:

<View>
    {Platform.OS === 'ios' ? <Text>Hi Apple!</Text> : <Text>Hi Android!</Text>}
 </View>

In styles:

cube: {
    width: Platform.OS === 'ios' ? 200 : 300,
    aspectRatio: 1
  }

The Platform module provides select method which can accept any type of args. With this flexibility, we can achieve the same effect as above but cleaner code:

const Logo = Platform.select({
  ios: () => require('Apple'),
  android: () => require('Android'),
})();
 
<Logo />;

In styles:

import {Platform, StyleSheet} from 'react-native';
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    ...Platform.select({
      ios: {
        backgroundColor: 'red',
      },
      android: {
        backgroundColor: 'blue',
      },
    }),
  },
});


5. Device Rotation

Many apps can work in portrait and landscape mode. If this is the case for our app , we have to ensure that the layout doesn’t break when changing orientation. As we can expect sometimes the layout can change drastically when we flip the device. Our components may need different styling depending on the orientation. Unfortunately, by default rotation of the device does not trigger a re-render. That’s why it has to be handled manually. We already have the knowledge required to build our own and it’s quite easy!

class RotateComponent extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      orientation: ''
    };
  }
 
  getOrientation = () => {
    if (Dimensions.get('window').width < Dimensions.get('window').height) {
      this.setState({ orientation: 'portrait' });
    } else { this.setState({ orientation: 'landscape' }); }
  };
 
  componentDidMount() {
    Dimensions.addEventListener('change', this.getOrientation);
  }
 
  render() {
    return (
      <Text>{this.state.orientation}</Text>
    );
  }
}

If we need to support orientation change across the app, it’s a good idea to use HOC to inject orientation.

const HOC = WrappedComponent => class extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      orientation: ''
    };
  }
  componentDidMount() {
    Dimensions.addEventListener('change', this.getOrientation);
  }
 
      getOrientation = () => {
        if (Dimensions.get('window').width < Dimensions.get('window').height) {
          this.setState({ orientation: 'portrait' });
        } else { this.setState({ orientation: 'landscape' }); }
      };
 
      render() {
        return <WrappedComponent {...this.props} orientation={this.state.orientation} />;
      }
};

We can also pass getOrientation to onLayout prop exposed by View component. It is fired on every layout change, so it should be used carefully.

If we want to take advantage of the orientation in our styles, remember that it should be inline styles. We already know how to trigger a re-render of the layout when the device is rotated, but the styles are loaded only once. That’s why styles which affect the layout on rotation should be placed inline.

That’s all about in this article.


Conclusion

In this article, We understood how to create Responsive Layouts in React Native. We reviewed responsive layouts challenges in React Native apps and provided solutions for making our responsive layouts much easier. Responsiveness solutions include techniques like Flexbox, dimensions, and aspect ratio properties. In addition, we can detect the device platform and screen orientation to adjust our app to different screen sizes. 

Thanks for reading ! I hope you enjoyed and learned about the Responsive Layout challenges and solutions in React Native. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!😊😊😊

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s