How to Show Images with Dynamic Height in React Native

Last Updated on October 27, 2020.

If you have worked with any apps with social feeds then you might have faced this issue. The images you receive from the server will have different heights and widths. As a mobile app developer, you may need to show them neatly with a fixed width and dynamic height. Let’s see how to show images with auto heights in react native.

There’s a third-party library named react native auto height image. It makes our task pretty easy. Using this library you don’t need to specify the height of the image. You can install it using the following command.

npm install react-native-auto-height-image

Showing images with unknown height can be done as given below.

<AutoHeightImage
 width={100}
 source={{uri: 'http://placehold.it/350x150'}}
 />

It’s not limited to remote images, you can also use local images.

<AutoHeightImage
 width={100}
 source={image}
 />

In the following react native example, I am passing few remote image links to a FlatList using this library.

import React from 'react';
import {StyleSheet, FlatList, Dimensions, View} from 'react-native';
import AutoHeightImage from 'react-native-auto-height-image';

const App = () => {
  const images = [
    {
      url:
        'https://cdn.pixabay.com/photo/2020/09/04/20/09/cartoon-5544856_960_720.jpg',
    },
    {
      url:
        'https://cdn.pixabay.com/photo/2020/05/15/13/28/reading-5173530_960_720.jpg',
    },
    {
      url:
        'https://cdn.pixabay.com/photo/2020/10/12/02/11/man-5647507__340.jpg',
    },
  ];
  return (
    <View style={styles.container}>
      <FlatList
        data={images}
        renderItem={({item}) => (
          <AutoHeightImage
            width={Dimensions.get('window').width}
            source={{uri: item.url}}
          />
        )}
      />
    </View>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});

You can see the variations in the heights in the output.

I hope this react native tutorial of Flatlist with images of different unknown heights will be helpful for you.

Leave a Reply

%d bloggers like this: