Reputation: 204
In the code below, there's an input form with a submit button. There's a map function which should display the items in items
(which is a state array). I wanted to attach a button to every item displayed - that when clicked on, it should delete that item in the state array.
function App() {
let [name, setName] = useState('')
let [items, setItems] = useState([{id:1, name:"aaryan"}, {id:2, name:"dewan"}])
const deleteItem = (id) => {
//code to delete the element
console.log("Hi World")
}
return(
<div>
<form>
<label>
Name:
<input type="text" name="name" onChang e={(e) => setName(e.target.value)}/>
<button type='submit'>Submit</button>
</label>
</form>
{
items.map((item) => {
return(
<div key={item.id}>
<h2>{item.name}</h2>
<button onClick={deleteItem(item.id)}>Delete</button>
</div>
)
})
}
</div>
)
}
The problem: When I type anything in the input box without clicking the delete button, deleteItem()
gets called 4 times and displays 'Hi World'! Why is that happening? And how do I fix it?
What I want - deleteItem()
should be called ONLY when I press the Delete button
Upvotes: 0
Views: 36
Reputation: 305
Replace
<button onClick={deleteItem(item.id)}>Delete</button>
with
<button onClick={() => deleteItem(item.id)}>Delete</button>
With the first approach you are directly calling the function on render()
, so whenever the page renders you are calling the deleteItem
function too.
Upvotes: 2