Reputation: 544
I want to disable not selected row when selected row > 3. I did it but I don't know how to get it back from disabling when selected row < 3. What should I do? I tried renderCell return normal Checkbox for selected.length < 3
but it doesn't work.
Here is my code: https://codesandbox.io/s/selection-ant-design-demo-forked-4s6uo?file=/index.js
Upvotes: 1
Views: 2081
Reputation: 5497
No need to have an additional state for the row selection. The onChange prop of the rowSelection gives you the selected rows . we just need to map over it to get the row keys .
onChange: (selectedRowKeys, selectedRows) => {
setSelected(selectedRows.map(row => row.key))
},
Once you have the row keys, now all we need to do is to check whether a row key is not part of the selected keys . If the selected rows is greater than 2 and the row's key is not in the selected keys then we are disabling it .
getCheckboxProps: (record) => {
if (selected.length > 2) {
return {
disabled: !selected.includes(record.key)
};
}
}
Complete Code
const Demo = () => {
const [selected, setSelected] = useState([]);
return (
<Table
rowSelection={{
onChange: (selectedRowKeys, selectedRows) => {
setSelected(selectedRows.map(row => row.key))
},
getCheckboxProps: (record) => {
if (selected.length > 2) {
return {
disabled: !selected.includes(record.key)
};
}
}
}}
columns={columns}
dataSource={data}
/>
);
};
Working Sandbox
Upvotes: 1