How to set image width to be 100% and height to be auto in React Native?

Sometimes, we want to set image width to be 100% and height to be auto in React Native.

In this article, we’ll look at how to set image width to be 100% and height to be auto in React Native.

How to set image width to be 100% and height to be auto in React Native?

To set image width to be 100% and height to be auto in React Native, we can set the width and height of the Image.

For instance, we write:

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

export default function App() {
  const win = Dimensions.get('window');
  const ratio = win.width / 200;

  return (
    <View
      style={{
        flexGrow: 1,
      }}>
      <Image
        source="https://picsum.photos/200/300"
        style={{
          width: win.width,
          height: 300 * ratio,
        }}
      />
    </View>
  );
}

to call Dimensions.get with 'window' to get the window’s dimension.

Then we calculate the ratio between the width and height of the image with win.width / 200, where 200 is the width of the image.

Then we set the width to win.width and the height to 300 * ratio where 300 is the height of the image.

Conclusion

To set image width to be 100% and height to be auto in React Native, we can set the width and height of the Image.