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.89k stars 1.12k forks source link

Is it possible to scroll to an item or reveal an item in a virtualized list or virtualized tree? #7212

Open alirv90 opened 3 days ago

alirv90 commented 3 days ago

๐Ÿ™‹ Documentation Request

I'm currently building a file explorer and would like to use a virtualized tree structure. However, I'm unsure how to implement scrolling to a specific item. Could someone please assist me with this? Thank you!

๐Ÿงข Your Company/Team

No response

snowystinger commented 2 days ago

Depends on the virtualizer possibly. For example, ours will render the currently state.selectionManager's current focus key regardless of if it is out of view or not. Meaning you could possibly set that, then focus the component and use scrollTo.

You may also be able to get a ref to the scrollview, then set the scrolltop to N*height of row or something like that.

However, other virtualizers may do different things. Could you provide an example in a codesandbox or stackblitz?

alirv90 commented 2 days ago

Hi @snowystinger, thank you for your response!

I'm working on implementing a FileExplorer in ./src/FileExplorer.tsx (Stackblitz: https://stackblitz.com/~/github.com/alirv90/justd-play).

Currently, to jump to an item e.g. Portfolio item with the ID 23, I need to mark it as the selected item and manually press the TAB key. I'm looking to implement a function to automatically scroll to the item by its ID (scrollToItem(id: Key)).

Any guidance you can provide would be greatly appreciated!

snowystinger commented 1 day ago

Unfortunately, there isn't really an easier way at the moment. I'll definitely leave this open to improve it.

In the meantime, I think you might be able to do it by getting access to the scrollRef in the Virtualizer. This is only available right now through a custom renderer. https://github.com/adobe/react-spectrum/blob/main/packages/react-aria-components/src/Virtualizer.tsx#L58

example of a custom renderer https://github.com/adobe/react-spectrum/blob/68e305768cb829bab7b9836dded593bd731259f3/packages/%40react-spectrum/s2/src/Breadcrumbs.tsx#L375

And then you'd want to do it the way I outlined above, where ref to scrollview is the scrollRef I'm referring to above

You may also be able to get a ref to the scrollview, then set the scrolltop to N*height of row or something like that.