Make Image fill parent, but keep ratio in react-native (dynamic/network images)

Viewed 11004
3 Answers

According to this official React-Native guide, if you want to make an image scale dynamically according to its parent element dimensions, you have to set the width and height of the image to undefined, and perhaps also add resizeMode="contain" to the image props. You can use this following styling to your image:

import { StyleSheet, Dimensions } from 'react-native;

// Get device width
const deviceWidth = Dimensions.get('window').width;

/*
image container dimension is dynamic depending on the device width
image will dimension will follow imageContainer's dimension
*/
const styles = StyleSheet.create({
  imageContainer: {
    height: deviceWidth * 0.8,
    width: deviceWidth * 0.8
  },
  image: {
    flex: 1,
    height: undefined,
    width: undefined
  }
});

export default styles;

I always use StyleSheet.absoluteFillObject. It will fill the parent's size. resizeMode can be contain, cover, stretch, center, repeat. Like this:

  image: {
    resizeMode: 'cover',
    ...StyleSheet.absoluteFillObject,
  },

While the solutions posted above work for local images, they don't work for network images. Here is why: https://facebook.github.io/react-native/docs/images#why-not-automatically-size-everything

The simplest solution for me was to calculate the height off my component based on the Dimensions height and the flex-portion my component takes in the view.
E.g. in my view the image component has a .85 flex, in a parent that has a 1 flex. So 100% height of the parent equals to:

Dimensions.get('window').height * 0.85
Related