I'm trying to add an active "x" button to each li so that a user can click on it to remove the li
from the list. I've added the button so that it appears with each list item, but I don't know what I would need to enter onClick
to remove the corresponding li after clicking. Any suggestions?
<div>
<h5 className="col-lg-4 mt-4">Selected Files</h5>
<ul className="nobull text-sm">
{files.map((file) => (
<li key={file.path}>
<Button className="ml-3" close />
{file.path} - {(file.size / 1024).toFixed(1)} KB
</li>
))}
</ul>
</div>
In case it helps anyone, after further research, I was able to get my answer. I created the following const:
const remove = file => {
const newFiles = [...files]; // make a var for the new array
newFiles.splice(file, 1); // remove the file from the array
setFiles(newFiles); // update the state
};
Then I updated my code as such:
<div>
<h5 className="col-lg-4 mt-4">Selected Files</h5>
<ul className="nobull text-sm">
{files.map((file, i) => (
<li key={file.path} className="py-2">
<Button className="ml-3" onClick={() => remove(i)} close />
{file.path} - {(file.size / 1024).toFixed(1)} KB
</li>
))}
</ul>
</div>;
You can try something like this:
const handleDelete = (index) => {
let filesArr = [...files];
filesArr.splice(index, 1); // This will delete the element
// Update the state with this modified array
setFiles(filesArr); // like this
}
<div>
<h5 className="col-lg-4 mt-4">Selected Files</h5>
<ul className="nobull text-sm">
{files.map((file, fileIndex) => ( // fileIndex is added here to hold array element index
<li key={file.path}>
<Button className="ml-3" close />
{file.path} - {(file.size / 1024).toFixed(1)} KB
<button type="button" onClick={() => handleDelete(fileIndex)}
</li>
))}
</ul>
</div>;
You can create the key array that you want to remove.
function Files(){
const [dis, setDis] = useState([]);
const removeHandler = (key) => {
setDis(dis.push(key))
}
return(
<div>
<h5 className="col-lg-4 mt-4">Selected Files</h5>
<ul className="nobull text-sm">
{files.map((file, key) => (
!fruits.includes(key) && (
<li key={file.path}>
<Button className="ml-3" close onClick={()={removeHandler(key)}}/>
{file.path} - {(file.size / 1024).toFixed(1)} KB
</li>
)
))}
</ul>
</div>;
)
}
you could use a function like this const removeFile = id =>{ const updatedFiles = files.filter(file => file.id !== FileId)
setFiles(updatedFiles)
}
<Button className="ml-3" onClick={() => removeFile(id)} close />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.