1

I have an array of image uri's which are presented in the UI as follows:

enter image description here

{this.state.ADImageArray.map((prop, key) => {

   return (
     <View style={PhotoStyles.imgThumbnailBlock}>
      <Image
        source={{uri: prop, isStatic: true}}
        style={PhotoStyles.imgThumbnail}
        />
        <TouchableOpacity onPress={this.removephoto} style={PhotoStyles.removePhotoLnk}>
          <Image
            source={require('../images/icons/ico-removeImg.png')}
            style={PhotoStyles.removePhotoImg}
          />
        </TouchableOpacity>
    </View>
   );
})}

I want an image to be removed from the array whenever the orange delete button is clicked.

I have the this.removephoto action ready - but wonder how can i remove a particular image in this context - is it possible to remove the image by key?

2 Answers 2

5

Yes it's possible for you to remove the item using it index. So your removephoto function can be of the form

removephoto = (index) => {
   let result = this.state.ADImageArray.filter((item, key) => key != index)
   this.setState({ADImageArray: result})
}

then you call it as follows

   <TouchableOpacity onPress={() => this.removephoto(key)} style={PhotoStyles.removePhotoLnk}>

Or alternatively you can remove the link by its url you just need to change the implimentation of the removephoto() function to the one below

removephoto = (url) => {
   let result = this.state.ADImageArray.filter((item, key) => item != url)
   this.setState({ADImageArray: result})
}

and then you call it as follows

   <TouchableOpacity onPress={() => this.removephoto(prop)} style={PhotoStyles.removePhotoLnk}>
Sign up to request clarification or add additional context in comments.

Comments

1

You can pass key to your click handler like so

<TouchableOpacity onPress={() => this.removephoto(key)}>

Be aware that this will create a new function each time, so for performance reasons it's better to bind the handler, like so:

<TouchableOpacity onPress={this.removephoto.bind(this, key)}>

Then your handler looks something like

removephoto = (key) => {
  const { ADImageArray } = this.state;
  this.setState({
    ADImageArray: ADImageArray.filter((item, i) => i !== key)
  });
}

Check out this working Expo snack

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.