I know there is a similar question on StackOverflow, but it is not answered for a two years now.
Is it possible to set selected items for DetailsList programmatically? I try to call selection.setKeySelected(... or selection.setIndexSelected(... but DetailsList doesn't reflect the changes, i.e. selection check boxes are not drawn according to the new selected state of rows.
...
const getSelectionDetails = (): string => {
const selectionCount = selection.getSelection().length;
return selectionCount
? `${selectionCount} items selected: ${selection.getSelection().map( (i: any) => i.key ).join('; ')}`
: 'No items selected';
}
...
const createSelection = () => {
return new Selection({
onSelectionChanged: () => setSelectionDetails(getSelectionDetails()),
getKey: (item: any) => item.key
});
};
...
const [selection, setSelection] = useState(createSelection());
const [selectionDetails, setSelectionDetails] = useState('');
...
return (
<Label>{selectionDetails}</Label>
<DetailsList
items={items}
columns={columns}
selectionMode={SelectionMode.multiple}
getKey={ (item: any) => item.key }
setKey="set"
layoutMode={DetailsListLayoutMode.justified}
isHeaderVisible={true}
selection={selection}
selectionPreservedOnEmptyClick={true}
enterModalSelectionOnTouch={true}
/>
<DefaultButton
onClick={
() => {
const newSelection = createSelection();
newSelection.setItems(items);
for (let i = 1; i <= 3; i++) {
newSelection.setKeySelected(`${i}`, true, false);
}
setSelection(newSelection);
setSelectionDetails(getSelectionDetails());
}
}
>
Select items programmatically
</DefaultButton>)
I do see answers in the Stack Overflow issue that address this question. I think the issue with the code you provided is that you are making a new Selection on every render. I've created a CodePen similar to your code which seems to work fine, the primary difference being that it doesn't create a new Selection on every render like your code does.
Thank you! Now it works as expected.
Most helpful comment
I do see answers in the Stack Overflow issue that address this question. I think the issue with the code you provided is that you are making a new
Selectionon every render. I've created a CodePen similar to your code which seems to work fine, the primary difference being that it doesn't create a newSelectionon every render like your code does.