0

I have two arrays,

const [imagesUrlArray, setURls] = useState([])

  const [imagesArray, setImages] = useState([])

using handle change below; imagesUrlArray is used to display the images on the screen, and imagesArray is saved to later update those same images to the database

const handleChange = (e) => {
    let selected = e.target.files[0]
        var selectedImageSrc = URL.createObjectURL(selected);
        addUrl(selectedImageSrc)
        addImage(selected)
    };

Though I now want to click the X(delete) button and remove the item at index of imagesUrlArray and imagesArray (say if the user no longer wants to use that image)

<div className="img-grid">
{ imagesUrlArray && imagesUrlArray.map((url,index) => {

  return ( <div  key={index}
    className="img-wrap">
       {/* <span class="close">&times;</span> */}
       <button onClick={ () => handleRemove(index)} className="close">X</button>
       
<img src={url} alt="uploaded" />
        </div>
)
   }
)}
</div>

I have tried splice and slice etc but still cannot find a perfect solution,

here is the handleRemove Function

const handleRemove = (index) => {

  
  const newImagesArray = imagesArray.splice(index);

  const newImagesUrlArray = imagesUrlArray.splice(index);

  setImages(newImagesArray);

  setURls(newImagesUrlArray);
}
0

1 Answer 1

2

You can do something like this:

const handleRemove = (index) => {

  setImages(imagesArray.filter((x,i) => i !== index));

  setURls(imagesUrlArray.filter((x,i) => i !== index));

}

So, basically the idea is to skip the element at specific index and return the remaining items and set the state.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, works a charm, have a great day or night.

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.