I'm using the grid api to get the selected rows by using the function getSelectedRows()
. However, the list of rows seems to be unordered, i.e the items are not in the order I selected them in.
Is there another way to get the selected rows in the order they were selected?
You can keep track of the selected items yourself and make sure it's chronologically ordered by listening to selectionChanged
event.
// global keyboard state, put this outside of the function body
// we need to store the current shift key state to know if user
// are selecting multiple rows
const KEYBOARD_STATE = {
isShiftPressed: false
};
document.addEventListener("keydown", (e) => {
KEYBOARD_STATE.isShiftPressed = e.key === "Shift";
});
document.addEventListener("keyup", (e) => {
KEYBOARD_STATE.isShiftPressed = false;
});
const [selection, setSelection] = React.useState([]);
const onSelectionChanged = (e) => {
const selectedNodes = e.api.getSelectedNodes();
const lastSelectedNode =
selectedNodes[0]?.selectionController?.lastSelectedNode;
// if lastSelectedNode is missing while multi-selecting,
// AgGrid will select from the first row
const selectedNodeFrom = lastSelectedNode || e.api.getRenderedNodes()[0];
const isRangeSelect = KEYBOARD_STATE.isShiftPressed;
const difference = (arr1, arr2) => arr1.filter((x) => !arr2.includes(x));
const newSelection = difference(selectedNodes, selection);
if (newSelection.length > 0) {
if (isRangeSelect) {
const isSelectBackward =
newSelection[0].rowIndex < selectedNodeFrom.rowIndex;
if (isSelectBackward) {
newSelection.reverse();
}
}
newSelection.forEach((n) => updateSelection(n));
} else {
updateSelection(); // deselect
}
};
const updateSelection = (rowNode) => {
setSelection((selections) => {
if (rowNode) {
const isSelected = rowNode.isSelected();
if (isSelected) {
return [...selections, rowNode];
} else {
return selections.filter((s) => s.id !== rowNode.id);
}
} else {
return selections.filter((n) => n.isSelected());
}
});
};
return (
<>
<pre>
{JSON.stringify(selection.map((n) => n.data.id))}
</pre>
<AgGridReact
rowSelection="multiple"
columnDefs={columnDefs}
rowMultiSelectWithClick
onSelectionChanged={onSelectionChanged}
{...}
/>
</>
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With