react-nativereact-native-flatlist

Add one last element to the end of FlatList


I am trying to achieve the following, whereas all but the last are normal images coming from an array.

Images

Currently this is the code for the FlatList:

<FlatList
  data={images}
  numColumns={3}
  // ListFooterComponent={
  // <View style={[StyleSheet.actionUploadedPictureFrame , {height: PIC_HEIGHT, width: PIC_WIDTH}]}>
  //     <Image source={require('../../../images/add-icon.png')} />
  // </View>}
  renderItem={ ({item, index}) => index == images.length -1 ?
     <View style={{flexDirection: 'row'}}>
       <Image style={[StyleSheet.actionUploadedPictureFrame , {height: PIC_HEIGHT, width: PIC_WIDTH}]} source={{uri: item.url}} /> 
       <View style={[StyleSheet.actionUploadedPictureFrame , {height: PIC_HEIGHT, width: PIC_WIDTH}]}>
         <Image source={require('../../../images/add-icon.png')} />
       </View>
     </View>
    : <Image style={[StyleSheet.actionUploadedPictureFrame , {height: PIC_HEIGHT, width: PIC_WIDTH}]} source={{uri: item.url}} /> }
  keyExtractor={(item, index) => index.toString()}
/>

Which long story short, renders the pictures in the array in a table of 3 columns, and checks for the last picture in the list and in addition to rendering the picture, it also renders this plus sign.

However this is bound to have some sort of error if the list has a number of elements multiple of 3, since the plus sign would most likely be out of the screen. If I use ListFooterComponent, it renders it in an entirely new line.

Does anyone know an effective work around to this?


Solution

  • Since I don't think I was clear enough, I'll try to explain properly my idea with this sample code:

        <FlatList
          data={[...images, { plusImage: true }]}
          numColumns={3}
          renderItem={({ item }) => {
            if (item.plusImage) {
              return (
                <View
                  style={[
                    StyleSheet.actionUploadedPictureFrame,
                    { height: PIC_HEIGHT, width: PIC_WIDTH }
                  ]}
                >
                  <Image source={require("../../../images/add-icon.png")} />
                </View>
              );
            }
            return (
              <Image
                style={[
                  StyleSheet.actionUploadedPictureFrame,
                  { height: PIC_HEIGHT, width: PIC_WIDTH }
                ]}
                source={{ uri: item.url }}
              />
            );
          }}
          keyExtractor={(item, index) => index.toString()}
        />;
    

    I don't know if it's the best practice to concat data array like that directly in the data prop, but you can always choose to declare it earlier in the render method. Let me know if this can fit your request.