How to pass the Key value of each list item via the button created inside the li tag to the function, so that i cant filter that element out and render new list.
Need to complete the handleDelete function
import { useState } from "react";
function MyComponent() {
const [foods, setFoods] = useState(["Apple", "Orange", "Banana"])
const handleSubmit = () => {
const newFood = document.getElementById("input-fruit").value;
document.getElementById("input-fruit").value = "";
setFoods(prevFoods => ([...prevFoods, newFood]))
}
const handleDelete = (idx) => {
console.log(idx);
// setFoods(foods.filter((el, idx) => console.log(idxx, idx)))
}
return (<>
<ul>
{foods.map((el, idx) => <li key={idx}> {el} <button key={idx} onClick={(idx) => handleDelete(idx)}>{`${idx}`}</button> </li>)}
</ul>
<input id="input-fruit" type="text" placeholder="Enter a food item" />
<button onClick={handleSubmit}>Submit</button>
</>);
}
export default MyComponent
2
Answers
You’re using the
map
callback asel
andidx
, but you’re defining theonClick
arrow function as(idx) =>
.The
onClick
will get the click event as first param, but you’re overwriting that.If you don’t need the click event, just use an empty arrow
() =>
For the
handleDelete
function, you cansplice
the array to remove it by index:The onClick handler is updated to
onClick={() => handleDelete(idx)}
. This ensures the correct index is passed when the button is clicked.Inside handleDelete, the setFoods function filters out the item at the specified index.
The filter function compares the current index of the item (
index
) with the index you want to delete (idx
). If they don’t match, the item remains in the array.You don’t need to set a
key
on the button itself; it’s only necessary for theli
elements to maintain uniqueness in the rendered list.