How to Show Images According to a Preferred Aspect Ratio in React Native?

Jan 02, 2023 . Admin

In this react native example, I will show you images in a 3/2 aspect ratio. The 3/2 aspect ratio is generally used to display images in portrait size.

In this example,We will set full image to mobile screen auto in react native.we set the height to undefined to keep the aspect ratio and set the aspectRatio property to set the aspect ratio of the image.The complete example below shows you how to do that.

Step 1: Download Project

In the first step run the following command to create a project.

expo init ExampleApp
Step 2: App.js

In this step, You will open the App.js file and put the code.

import React from 'react';
import { StyleSheet, Text, View, Image} from 'react-native';

export default function App() {
    return (
      <View style={styles.container}>
        <Image
        style={styles.img}
        source={require('./assets/tree.jpg')}
        />
      </View>
    );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  
  img: {
    width: '100%',
    height: undefined,
    aspectRatio: 3/2,
  }
});
Step 3: Run Project

In the last step run your project using the below command.

expo start

You can QR code scan in Expo Go Application on mobile.

Output:

It will help you...

#React Native