Row range select
Hi, I'd like to implement range select with shift + click, but I cannot find proper solution for this. There is possible way to modify this part with onChange function but I would like to use more cleaner way.
Is there anybody who implemented this? 🙂
cell: ({ row }) => (
<Checkbox
checked={row.getIsSelected()}
indeterminate={row.getIsSomeSelected()}
onChange={row.getToggleSelectedHandler()}
/>
),
cell: ({ row }) => (
<Checkbox
checked={row.getIsSelected()}
indeterminate={row.getIsSomeSelected()}
onChange={row.getToggleSelectedHandler()}
/>
),
1 Reply
flat-fuchsiaOP•3y ago
I implemented my custom hook like this ...
and used it in my checkbox component but its not ideal
export default function useRowSelection() {
const { shiftKeyRef } = useMetaKeys();
const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
const [lastRowSelectedIndex, setLastRowSelectedIndex] = useState<number | null>(null);
const setShiftRowSelection = (index: number, isSelected: boolean) => {
if (shiftKeyRef.current && lastRowSelectedIndex !== null) {
const min = Math.min(index, lastRowSelectedIndex);
const max = Math.max(index, lastRowSelectedIndex);
const newlySelectedIndexes: RowSelectionState = {};
for (let i = min; i <= max; i++) {
newlySelectedIndexes[i] = !isSelected;
}
setRowSelection({
...rowSelection,
...newlySelectedIndexes,
});
} else {
setRowSelection({
...rowSelection,
[index]: !isSelected,
});
}
setLastRowSelectedIndex(index);
};
return { rowSelection, setRowSelection, setShiftRowSelection } as const;
}
export default function useRowSelection() {
const { shiftKeyRef } = useMetaKeys();
const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
const [lastRowSelectedIndex, setLastRowSelectedIndex] = useState<number | null>(null);
const setShiftRowSelection = (index: number, isSelected: boolean) => {
if (shiftKeyRef.current && lastRowSelectedIndex !== null) {
const min = Math.min(index, lastRowSelectedIndex);
const max = Math.max(index, lastRowSelectedIndex);
const newlySelectedIndexes: RowSelectionState = {};
for (let i = min; i <= max; i++) {
newlySelectedIndexes[i] = !isSelected;
}
setRowSelection({
...rowSelection,
...newlySelectedIndexes,
});
} else {
setRowSelection({
...rowSelection,
[index]: !isSelected,
});
}
setLastRowSelectedIndex(index);
};
return { rowSelection, setRowSelection, setShiftRowSelection } as const;
}
<Checkbox
checked={row.getIsSelected()}
indeterminate={row.getIsSomeSelected()}
onChange={() => {onShiftRowSelectionChange(row.index, row.getIsSelected());}}
/>
<Checkbox
checked={row.getIsSelected()}
indeterminate={row.getIsSomeSelected()}
onChange={() => {onShiftRowSelectionChange(row.index, row.getIsSelected());}}
/>