I am trying to pass selected row id to handleDelete() when Button is pressed. For some reason its sending id's of all objects inside array. But I only want to capture selected row id and send it to handleDelete function.
const columns = [
{
title: 'Action',
key: 'action',
sorter: true,
render: (text, row) => (
<Space size="middle">
<Button onClick = {handleDelete(row.id)} type="text"> Delete </Button>
</Space>
),
},
]
My table component
<Table
{...tableProps}
pagination={{
position: [top, bottom],
}}
columns={tableColumns}
dataSource={hasData ? data : []}
scroll={scroll}
/>
Function to recieve id : ( I am sending the ID's but its logging all the ID's )
const handleDelete = (id) => {
console.log(id)
}
CodePudding user response:
Passing handleDelete(row.id)
to onClick
causes handleDelete
to be called for each item during render time of the component.
Change the callback of onClick
event handler for delete button, in a way that an arrow function returns handleDelete
:
<Button onClick = {() => handleDelete(row.id)} type="text">
Delete
</Button>
CodePudding user response:
You should write your delete function like this
const handleDelete = (id) => () => {
console.log(id)
}
// Usage
const columns = [
{
title: 'Action',
key: 'action',
sorter: true,
render: (text, row) => (
<Space size="middle">
<Button onClick={handleDelete(row.id)} type="text"> Delete </Button>
</Space>
),
},
]
and another way, use bind
like this:
const handleDelete = (id) => {
console.log(id)
}
// usage
const columns = [
{
title: 'Action',
key: 'action',
sorter: true,
render: (text, row) => (
<Space size="middle">
<Button onClick={handleDelete.bind(this,row.id)} type="text"> Delete </Button>
</Space>
),
},
]
One option remaining, use dataset attribiutes:
const handleDelete = (e) => {
console.log(e.target.dataset.id)
}
// usage
const columns = [
{
title: 'Action',
key: 'action',
sorter: true,
render: (text, row) => (
<Space size="middle">
<Button data-id={row.id} onClick={handleDelete} type="text"> Delete </Button>
</Space>
),
},
]