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">×</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);
}