I’m using the Autocomplete component from Material-UI in a project. Since I have a lot of options to render, virtualization would be very beneficial. So I started from the virtualized example in the docs with react-window
. Everything worked great, but the project already has a dependency on react-virtualized
and I would like to avoid adding a new one that solves something similar. So based on the react-window
example, I tried to re-implement it using List
from react-virtualized
.
Code Sample
The Problem
As demonstrated in the sandbox above, it’s kind of working. What doesn’t work is the keyboard navigation. You can navigate using the keyboard, but the Listbox
doesn’t scroll to the highlighted value when you navigate outside of the visible elements.
What I’ve tried:
- Overriding
onKeyDown
for theAutocomplete
component. This however completely overrides the keydown functionality, requiring me to re-implement it. - Using
onKeyUp
to keep theonKeyDown
functionality and finding the element with thedata-focus
attribute, and then usingscrollToIndex
on theList
component. This works for some cases, but if the user holds down the key for a while and ends up on an index outside of the overscan rendered items it breaks.
Does anyone have a good way of using react-virtualized
to virtualize the options in the Material-UI Autoselect component? Should I be using something other than List
?
My final resort would be to use the useAutocomplete
hook and just re-implement the rendering logic, but since I’m only after the virtualization I’d like to avoid this if possible.
Advertisement
Answer
I managed to get it working thanks to an answer in an issue I opened about this on the Material-UI repo.
To get the scroll functionality working you need to make sure that the scrolling element has the role of “listbox”.
This is an updated example of the code demonstrating a working version: https://codesandbox.io/s/adoring-saha-n9cr1
The only thing changed is extracting the role
property from the ListboxComponent props and assigning it to the List
component.