I have a table in which each row has a button that would send a DELETE request to delete that row's data from database:
{
title: '',
render: (record) => {
return (
<Button icon={<DeleteOutlined />} style={{color:'#1890ff', border:'solid 0px'}} onClick={() => showModal(record)}
>
</Button>
)
}
},
Here I'm trying to pass the record data when clicking on the button to a modal. To do that I created a useState hook that would store my table row's data and then I wanted to pass the data to a modal:
const [modalTaskId, setModalTaskId] = useState();
const [visible, setVisible] = useState(false);
const showModal = (record) => {
setModalTaskId(record);
setVisible(true);
};
This is my modal:
<Modal
visible={visible}
onOk={() =>{handleOk()}}
confirmLoading={confirmLoading}
onCancel={handleCancel}
>
<p>{modalText}</p>
</Modal>
And let's say I want to log the modalTaskId when clicking ok on modal:
const handleOk = async () => {
console.log('modalTaskId: ', modalTaskId)
}
But it logs empty for me! So how can I pass data from my table's row to my modal and then use that data when clicking on modal's ok button?
Essentially, depending on the scope of your columns object, you can wrap them as a return value in a function that captures the context of your showModal handler.
const getColumns(showModal) {
return [{
title: "Buttons",
dataIndex: 'arbitrary',
render: (text, record) =>
<Button onClick={showModal}>Open Modal</Button>
}, ...]
}
...
// Usage
<Table dataSource={dataSource} columns={getColumns(showModal)} />
Note that this may not be the most performant solution.
At the first, set the Initial value for your modalTaskId.
const [modalTaskId, setModalTaskId] = useState();
Then, remove onOk, You can control your visibility by useEffect:
useEffect(() => {
if (visible) console.log(modalTaskId);
}, [visible])