How to Build Responsive Apps in React Native
Tags: reactnative
Published: 2021-04-01 13:40:06

React Native is a JavaScript (JS) framework that you can use to develop mobile applications. It supports building iOS and multi-platform Android apps from native user interface (UI) elements. React Native is based on Babel transformers and the JavaScriptCore runtime. React Native has [built-in support for continuous deployment](https://www.reactnative.guide/11-devops/11.0-devops.html) and [DevOps practices](https://cloud.netapp.com/devops).

React Native was created by Facebook during an internal hackathon in 2013 and made publicly available in 2015. Since its release, it has been widely used by developers wishing to build native mobile apps and functional UIs. In this article, you’ll learn how to build responsive apps in react native, including an example.
## Methods for Making React Native Apps Responsive
Although React Native does not include support for media queries, there are still several ways you can build responsive apps. Below are the most common methods to [optimize images](https://cloudinary.com/blog/image_optimization_for_websites_beautiful_pages_that_load_quickly), videos, and web elements when building responsive apps with React Native.
### Flexbox
Flexbox is a CSS module you can use to control a two-dimensional layout, similar to CSS Grid Layout. It includes a variety of properties you can use to automatically adapt your layout proportionally to various screen sizes. 

There are several important properties to know if you want to use flexbox effectively:

* *flex*—defines how your elements fill the available space. This number is proportional to other flex elements in the same container.
* *flexBasis*—defines the default size of an element along the main axis.
* *flexGrow*—defines how extra space should be assigned to elements within a container.
* *flexShrink*—defines how elements should shrink to prevent overflowing a container.

To use these properties, you assign the properties to the elements you want to define, and a number to each property itself. Assigning a 0 makes the dimensions static. Assigning a floating-point number larger than 0 adapts the element according to the property the number is assigned to. For example, imagine two elements in the same container; element A has *flex: 2* and element B has *flex: 3*. Element A takes up 2/5ths of the container and B takes 3/5ths. 

Other important properties to know include:

* *flexDirection*—defines the direction in which elements are flexed; either row or column. The default setting is a column, because mobile devices are typically elongated in shape. 
* *justifyContent*—defines how elements are spread within a container along the main axis. 
* *alignItems*—defines how elements are spread on the cross-axis. This property works similarly to justifyContent but along the perpendicular axis to the main axis.

### aspectRatio
Another property you can use is *aspectRatio*, which controls the size of undefined dimensions of an element. For example, if only the *height* is specified, *aspectRatio* ensures that the width scales accordingly. This property is exclusive to React Native and is not used in CSS.
### Screen Dimensions
When designing responsive sites, you often need to create different layouts for different device types or screen dimensions. Since React Native does not support media queries, this can be a challenge. However, you can access this same information using the Dimensions API.

You can use this API as follows:
```
import { Dimensions } from 'react-native';
 
const {width, height} = Dimensions.get(‘window');
```
Alternatively, if you are using React Native 0.61: 
```
const {width, height} = useWindowDimensions();
```
After you obtain your dimensions, you can set breakpoints defining when your layout should change. These changes can include different media sizes, layout configurations, or behaviors.

For example:
```
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>
    );
  }
}
```
### react-native-responsive-screen Library
*react-native-responsive-screen* is a library you can use to code UI elements responsively. It includes methods for responsive sizing, automatic re-rendering, and screen orientation detection. 

To use *react-native-responsive-screen* you need to perform the following:

1. Install the package with *npm install* *react-native-responsive-screen --save*. When your application runs, it will automatically detect the client screen width and height.
2. Use the two values *widthPercentageToDP()* and *heightPercentageToDP()* with a string percentage (i.e ‘50%’) in the brackets as your respective width or height values. 

When using this library, you can use it in combination with flexbox for greater control. Also, it is suggested that you start with the largest screen you want to support and work your way down. This helps prevent forgetting to add responsive values for all of your type number properties.
## Realistic Example: Building a Chat App
Building a chat app is a simple way to practice using the responsive methods covered above. This example is excerpted from a full tutorial created by [Akshay Kadam](https://heartbeat.fritz.ai/handling-responsive-layouts-in-react-native-apps-1494b3f85984?gi=c6ac096b9802).

1. Start by installing the *react-native-responsive-screen* library.
2. Download and store your graphic elements in your *assets/* folder. In this case, you’re using [pikachu_heart_eyes.png](https://github.com/deadcoder0904/responsive-react-native-layout/blob/master/assets/pikachu_heart_eyes.png).
3. In your App.js file, add the following code. 
Note that *SafeAreaView* ensures that content stays within the boundaries of the device and *ScrollView* enables you to scroll to overflow content.
```
import React from 'react'
import{ Image, SafeAreaView, ScrollView, StyleSheet, Text } from 'react-native'
import {
 heightPercentageToDP as hp,
 widthPercentageToDP as wp,
} from 'react-native-responsive-screen'

export default function App(){
 return (
    <SafeAreaView style={styles.container}>
      <ScrollView>
        <Image
        source={require('./assets/pikachu_heart_eyes.png')}
        style={styles.img}
        />
      </ScrollView>
    </SafeAreaView>
 )
}

const styles = StyleSheet.create({
  container:{
    flex: 1,
    backgroundColor: 'black',
  },
  img:{
    width: wp('70%'),
    height: hp('30%'),
    alignSelf: 'flex-end',
    resizeMode: 'contain',
  },
})
```
4.Add example chats as test content. An example of content is found below.
```
const chats = [
 { name: 'Prem', text: 'Hey, what’s up?' },
 { name: 'Pooja', text: 'Nothing, just studying. Why?' },
 { name: 'Prem', text: 'I just won tickets to a concert and have no one to go with...' },
 { name: 'Prem', text: 'You wanna go?' },
 { name: 'Pooja', text: 'Yeah! ' },
 { name: 'Prem', text: 'Perfect! It’s at 8 tonight' },
 { name: 'Pooja', text: 'Great!! I’ll meet you at your house at 7' },
]
```
5.Include the code below your image tag to style the chat content:
```
{chats.map((chat, i) => (
  <Text
    key={i}
    style={[
      styles.commonChat,
      chat.name === 'Prem' ? styles.rightChat : styles.leftChat,
    ]}
  >
    <Text style={styles.username}>@{chat.name}: </Text>
    {chat.text}
  </Text>
))}

commonChat: {
 color: 'white',
 borderRadius: 10,
 borderWidth: 1,
 borderColor: 'white',
 overflow: 'hidden',
 padding: 10,
 margin: 10,
 fontSize: hp('1.6%'),
},
leftChat: {
 backgroundColor: '#c83660',
 alignSelf: 'flex-start',
},
rightChat: {
 backgroundColor: 'rebeccapurple',
 alignSelf: 'flex-end',
},
username: {
 fontWeight: 'bold',
},
```
6.Test your app to ensure it scales correctly.

## Conclusion
Hopefully, this article helped you understand how you can build responsive apps in react native. While this article reviewed four popular methods, there are many more options, each suited for different projects. As you gain more experience, you’ll figure out your own methods, and the process will become much more familiar and faster.