adobe / react-spectrum

A collection of libraries and tools that help you build adaptive, accessible, and robust user experiences.
https://react-spectrum.adobe.com
Apache License 2.0
12.93k stars 1.12k forks source link

Add Collection.getAt #2138

Closed stephenh closed 3 years ago

stephenh commented 3 years ago

🙋 Feature Request

Add a way to do index-based lookups to @react-types Collection.

Collection's docs, "A generic interface to access a readonly sequential collection of unique keyed items", make it sound like doing an index-based lookup would be kosher.

🤔 Expected Behavior

Just do a lookup.

😯 Current Behavior

We have to convert collection.getKeys to an array, and do an index-based look up on the array to get the key, then Collection.getItem(key):

        <Virtuoso
          totalListHeightChanged={setListHeight}
          totalCount={state.collection.size}
          itemContent={(idx) => {
            // MapIterator doesn't have at/index lookup so make a copy
            const keys = [...state.collection.getKeys()];
            const item = state.collection.getItem(keys[idx]);
            if (item) {
              return <Option key={item.key} item={item} state={state} />;
            }
          }}
        />

🔦 Context

We're integrating useListBox / useMultipleSelectionState with react-virtuoso for virtualized rendering, and the virtuoso api has a itemContent: (index) => ReactNode method, that we want to implement by doing state.collection.getAt(index), where state is a SelectState.

devongovett commented 3 years ago

This seems reasonable. We generally try to avoid accessing collections by index where possible because indices can change as items are added, removed, or re-arranged within the collection. But your usecase seems like it would be ok because the indices are only used during rendering and not persisted anywhere.