I have a scenario here
const Parent = () => {
handleClick = (id) => {
console.log(id)
}
return <div>
users.map((user, index) =>
<child key={index} onClick={(user.id)=>handleClick(user.id)} />)
</div>
}
The child is using React.memo so it won’t re-render unless its props are changed. I don’t want the child to be re-render when the parent renders but in this scenario it will re-render because I am using an anonymous function. I can put handleClick inside of useCallback but how can I avoid the anonymous function here. I have to use an anonymous function here because I am expecting some arguments here.
You can try using bind.
const Parent = () => {
handleClick = (id) => {
console.log(id)
}
return <div>
users.map((user, index) =>
<Child key={index} onClick={handleClick.bind(this, user.id)} />)
</div>
}
Here's the relevant section of the React docs: Passing Arguments to Event Handlers
Although this is an old question, this is the approach I would take (in case it helps somebody else)
id={user.id}onClick attribute, and extract the attributes from the event.target in your handler functionNOTE: you don't have to pass the event argument, thus no need to build an anonymous function
const Parent = () => {
const handleClick = (event) => {
const {id} = event.target
console.log(id)
}
return users.map((user, index) =>
<div key={index} id={user.id} onClick={handleClick}>{user.name}</div>)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With