Brian Deterling
Brian Deterling

Reputation: 13724

Select Newly Added Row in Office UI Fabric DetailsList

I have a DetailsList for which I need to keep track of the current selection. My problem is I need to update my state when the user changes the selection, but also be able to set the selection when a new row is added. If I'm listening to user events via onSelectionChanged, I can't call setSelectionKey because it will just cycle back and forth.

Possibly related is that since I am adding a new row, I can't select it until the render that repopulates the items, but I'm not sure when I would even call setSelectedKey to ensure that's already done.

I have a version that kind of works by setting a flag to call setItems and then setSelectedKey while temporarily telling onSelectionChanged to ignore it, but I believe it's causing extra renders and doesn't work in all situations.

Thanks for any guidance.

Upvotes: 0

Views: 1066

Answers (1)

Brian Deterling
Brian Deterling

Reputation: 13724

I figured it out. The problem was I was just setting the previously selected item to selected, e.g. selection.setKeySelected(item.id, true). The secret turned out to be setting all of the other items to not be selected. Here are the relevant parts:

const selection = new Selection({ 
  getKey: item => item.id,
  onSelectionChanged: () => {
    the_chosen_one = selection.getSelection()[0];
    // ... do whatever with the item the user just selected ...
  }
});

...

// In some handler when you need to select/re-select an item:
const onWhatever = () => {
  setChangeEvents(false);
  state.items.forEach(item => {
    selection.setKeySelected(item.id, item.id === the_chosen_one.id);
  });
  setChangeEvents(true);
};

...

<DetailsList selection={selection} items={state.items} ...

I'm not sure the setChangeEvents part is necessary, but it didn't hurt. The documentation on this is non-existent so the only way to figure it out is reading the code and browsing through Github issues, but a lot of those turned out to be dead ends. I still don't understand why I have to explicitly de-select items that were never selected in the first place, but that's what it was.

I hope this helps someone else some day.

Upvotes: 1

Related Questions