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

Sometimes you may want to show images according to a given aspect ratio instead of a fixed height. Let’s check how to show images with a predefined aspect ratio in react native.

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

We must define the height and width while using the Image component. The trick is to define the height as undefined. Then provide your preferred aspect ratio to the style prop aspectRatio. See the code snippet given below.

<Image
        source={{
          uri: 'https://cdn.pixabay.com/photo/2022/03/20/15/40/nature-7081138_1280.jpg',
        }}
        style={{height: undefined, width: '100%', aspectRatio: 2 / 3}}
      />

Following is the complete react native code to show an image in a fixed aspect ratio.

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

const App = () => {
  return (
    <View>
      <Image
        source={{
          uri: 'https://cdn.pixabay.com/photo/2022/03/20/15/40/nature-7081138_1280.jpg',
        }}
        style={{height: undefined, width: '100%', aspectRatio: 2 / 3}}
      />
    </View>
  );
};

export default App;

Following is the output of the example.

This react native tutorial is created with react native 0.69 version and it is working on both Android and iOS devices flawlessly.

Similar Posts

Leave a Reply