How to show Images with Dynamic Height in React Native

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 display images with auto height 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 any of the following commands.

npm install react-native-auto-height-image

or

yarn add react-native-auto-height-image

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

<AutoHeightImage
        width={100}
        source={{uri: 'https://vivaxy.github.io/404'}}
        fallbackSource={image}
      />

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

In the following react native example, I am passing a 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';
import FallbackImage from './cat.jpg';

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}}
            fallbackSource={FallbackImage}
          />
        )}
      />
    </View>
  );
};

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

export default App;

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: