Reputation: 2689
I have implemented a Table using the react-virtualized Table component. I have added a checkbox column in the table and now want to implement the select all/select row functionality using those checkboxes.
Now, for adding select all/select row functionality, I am using react hooks for changing the checked
prop of CheckBox
but it doesn't seem to work. Below is the code link and when I scroll down the page with actual data, the checkbox checked state is removed.
Here's the code that I am trying to do, checked
is always remaining false for rows except for the header. Header select all is functioning fine
...
import {Checkbox} from 'semantic-ui-react';
const[selectAll, setSelectAll] = useState(false):
const checked = [];
function _checkboxState(data) {
if (checked.includes(data.index)) {
checked.pop(data.index);
} else {
checked.push(data.index);
}
}
<Column
disableSort
dataKey="checkbox"
width={30}
headerRenderer={() => (
<Checkbox
checked={selectAll}
onChange={() => {
if (selectAll === true) {
setSelectAll(false);
} else {
setSelectAll(true);
}
}}
/>
)}
cellRenderer={({rowIndex}) => (
<Checkbox
checked={selectAll || checked.includes(rowIndex)}
onChange={(e, data) => {
_checkboxState(data);
}}
index={rowIndex}
/>
)}
/>
...
Any help on this is appreciated!
Upvotes: 2
Views: 3559
Reputation: 2689
In the meantime, while I was waiting for an answer, I spent more time and found that I was mutating checked
and not using useState
hook.
This is the updated code:
.....
const [checked, setChecked] = useState([]);
const _onChangeHeaderCheckbox = data => {
data.checked ? setChecked(sortedList.map(row => row.id)) : setChecked([]);
};
const _onChangeRowCheckbox = data => {
const newRow = sortedList[data.index].id;
checked.includes(newRow)
? setChecked(old => old.filter(row => row !== newRow))
: setChecked(old => [...old, newRow]);
};
....
<Column
disableSort
dataKey="checkbox"
width={30}
headerRenderer={() => (
<Checkbox
indeterminate={
checked.length > 0 && checked.length < sortedList.length
}
checked={checked.length === sortedList.length}
onChange={(e, data) => _onChangeHeaderCheckbox(data)}
/>
)}
cellRenderer={({ rowIndex }) => (
<Checkbox
checked={checked.includes(sortedList[rowIndex].id) === true}
onChange={(e, data) => _onChangeRowCheckbox(data)}
index={rowIndex}
/>
)}
/>
....
Here's the working preview with dummy data:
Upvotes: 2