S.Hashmi
S.Hashmi

Reputation: 501

Remove item from FlatList in react native

I am using Flat List in react native to select Multiple images from gallery. Now i want to remove some of image before uploading it to server. I am not sure how to perform that action.

Here is my code...

<FlatList
          style={{ paddingBottom: 5, paddingTop: 10 }}
          data={this.state.imagesAddFile}
          keyExtractor={(y, z) => z.toString()}
          renderItem={({ item }) => (
            <SelectedLayout
             ImageName = {item.name}
            />
          )}
        />

Here i am getting list of images properly but not sure how to delete image from list please suggest am answer. Thanks

Upvotes: 0

Views: 9592

Answers (3)

Romit Kumar
Romit Kumar

Reputation: 3300

Since you code is not complete in your question, I assume that your SelectedLayout component might be having TouchableOpacity or something similar to handle tap (to select or remove image). Basically what you want is to modify the datasource of your Flatlist (i.e this.state.imagesAddFile array) from SelectedLayout component.

Create a function in the component containing the flatlist that receives the image name (or image url depending on the structure of your image object) and that function should remove that image from your state (imagesAddFile). Now pass this function as a prop to your SelectedLayout and call this function from SelectedLayout component in onPress of your Touchable**** in SelectedLayout. You can use lodash methods are they are very handy and well written.(You'd be using them a lot)

Your component might look something like this:

handleImageTap = (imageName) => {
   const { imagesAddFile } = this.state;
   this.setState({
      imagesAddFile: _.filter(imagesAddFile,imageObj => 
       imageObj.name !== imageName);
   })
}

render() {
  return(
   <FlatList
     style={{ paddingBottom: 5, paddingTop: 10 }}
     data={this.state.imagesAddFile}
     keyExtractor={(y, z) => z.toString()}
     renderItem={({ item }) => (
       <SelectedLayout
        ImageName = {item.name}
        handleImageTap = {this.handleImageTap}
       />
     )}
  />
  )

The line

_.filter(imagesAddFile,imageObj => imageObj.name !== imageName);

is nothing but just a JSX shorthand inside lodash filter method, which is taking imagesAddFile array, iterating over it and returning new array by removing the image object which is having the name equal to image name. Please refer the doc for better clarification.

Ideally you should be checking first whether the image exist in the array or not. Also i'd suggest not to play with image name, use something unique like id, or imageUrl

Upvotes: 1

TheMAS
TheMAS

Reputation: 21

Well, you could remove the desired item based on it's index.start with modifying the flatList

<FlatList
          style={{ paddingBottom: 5, paddingTop: 10 }}
          data={this.state.imagesAddFile}
          keyExtractor={(y, z) => z.toString()}
          renderItem={({ item,index }) => (
            <SelectedLayout
             onPress={(index) =>this.removeItemFromList(index)} 
             ImageName = {item.name}
            />
          )}
        />

you should wrap the component SelectedLayout inside a TouchableOpacity in order to implement onPress or whatever way you like it. if you could provide me with it's code I could show you.

now the removeItemFromList Implementation we're gonna use splice to remove it from imagesAddFile state.

removeItemFromList(index){
   let newimagesAddFile = this.state.imagesAddFile;
   newimagesAddFile.splice(index,1); //to remove a single item starting at index
   this.setState({imagesAddFile:newimagesAddFile})
}

Upvotes: 2

Rahul Mishra
Rahul Mishra

Reputation: 4583

I am using delete function like below method sharing all the code here:

Step 1: Render view in add a TouchableOpacity like below code:

<TouchableOpacity onPress={() => this.deleteAddress(itemData.item._id)}>
                <Icon name="trash" style={{paddingLeft: 10,paddingRight:10}} size={20} color="red" />
              </TouchableOpacity>

Step 2: Add a confirmation box like below code:

deleteAddress(id) {
    Alert.alert(
      'Delete Address',
      'Are you sure want to delete this address ?',
      [
        {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
        {text: 'OK', onPress: () => this.deleteAddressDetail(id)},
      ],
      { cancelable: false }
    )
  }

Step 3: Call your API or anything here:

deleteAddressDetail(id) {
  //Delete api or anything here
  //after that call your list so updated state data will render
}

Your updated flatlist code:

<FlatList
        data={this.state.addressList}
        keyExtractor={this._keyExtractor}
        extraData={this.state}
        renderItem={this.renderRowItem}
      />

Use render item like below code:

renderRowItem = (itemData) => {
  <TouchableOpacity onPress={() => this.deleteAddress(itemData.item._id)}>
                    <Icon name="trash" style={{paddingLeft: 10,paddingRight:10}} size={20} color="red" />
                  </TouchableOpacity>
}

Upvotes: 3

Related Questions