Ahalya Raj
Ahalya Raj

Reputation: 91

How to get index of the clicked images which is an item of array using React native

I made an array to get 5 images from users. I need to provide the functions for user to select and delete the images from that array dynamically. I am currently using splice() method to do the operation. but when i choose the image to delete..it is deleting the whole images onPress

renderImages = () => {
  let image = [];
  this.state.image.slice(0, 5).map((item, index) => {
    image.push(
      <View key={index} style={{ padding: 16 }}>
        <Image source={{ uri: item }} style={{ width: 60, height: 60 }} />
        <Icon
          name="window-close"
          size={15}
          color="#d3d3d3"
          style={{ position: "absolute", top: 5, right: 5 }}
          onPress={index => {
            this.setState({ image: this.state.image.splice(index, 1) });
          }}
        />
      </View>
    );
  });
  return image;
};

Upvotes: 2

Views: 891

Answers (2)

johannchopin
johannchopin

Reputation: 14843

Problem here is that you make a mutation directly on the state using splice. You need first to make a clone of the state:

renderImages = () => {
  let image = [];
  this.state.image.slice(0, 5).map((item, index) => {
    image.push(
      <View key={index} style={{ padding: 16 }}>
        <Image source={{ uri: item }} style={{ width: 60, height: 60 }} />
        <Icon
          name="window-close"
          size={15}
          color="#d3d3d3"
          style={{ position: "absolute", top: 5, right: 5 }}
          onPress={index => {
            let images = [...this.state.image]
            images.splice(index, 1)

            this.setState({ image: images });
          }}
        />
      </View>
    );
  });
  return image;
};

Upvotes: 1

vindev
vindev

Reputation: 2280

First of all don't mutate the state directly, more on this here. splice doesn't retun the updated array instead it returns the array of deleted elements.

renderImages = () => {
    let imagesToDisplay = [];
    const allImages = this.state.image;
    allImages.slice(0, 5).map((item, index) => {
        imagesToDisplay.push(
        <View key={index} style={{ padding: 16 }}>
    <Image source={{ uri: item }} style={{ width: 60, height: 60 }} />
        <Icon
        name="window-close"
        size={15}
        color="#d3d3d3"
        style={{ position: "absolute", top: 5, right: 5 }}
        onPress={index => {
            const image = this.state.image;
            image.splice(index, 1);
            this.setState({ image });
        }}
        />
        </View>
    );
    });
    return imagesToDisplay;
};

Upvotes: 1

Related Questions