I am trying to make multiple files upload, and have preview. If the image is click it will be deleted from array.
I already can delete the file from the array, but the problem is the component didn't update after i delete the data.
Here are the CodeSandbox
Here is my Code :
import { useState } from "react";
import "./Upload.css";
const Upload = () => {
const [file, setFile] = useState([]);
console.log(file);
const handleUpload = (e) => {
setFile([...file, ...e.target.files]);
};
const deleteFile = (index) => {
if (file !== []) {
var newArr = file;
newArr.splice(index, 1);
console.log(newArr, "after");
setFile(newArr);
}
};
return (
<div>
<input type="file" onChange={(e) => handleUpload(e)} multiple />
<br />
<br />
{file !== [] &&
file.map((data, index) => (
<div key={index}>
<img
src={URL.createObjectURL(data)}
alt="file-img"
className="image-preview"
onClick={() => deleteFile(index)}
/>
</div>
))}
</div>
);
};
export default Upload;
The image didn't removed after i click. but the files in array get deleted. Thank you before!