Home > Blockchain >  Auto scroll to a particular option in the Autocomplete
Auto scroll to a particular option in the Autocomplete

Time:10-03

Suppose I have a list of items in the dropdown or Autocomplete in Material-UI, how can one auto-scroll to the desired item in the list when I just tap on the drop down, for example in the list of top100Films, I already have the items, meaning when I open the dropdown, it first shows:

{ label: 'The Shawshank Redemption', year: 1994 }

What I want to achieve is, when I open the dropdown the list of items should start at an Item I want e.g:

{ label: 'Inception', year: 2010 }

Should appear as the first, but the list of the dropdown should auto-scroll to that item.

Below is the entire code:

import * as React from 'react';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';

export default function ComboBox() {
  return (
    <Autocomplete
      disablePortal
      id="combo-box-demo"
      options={top100Films}
      sx={{ width: 300 }}
      renderInput={(params) => <TextField {...params} label="Movie" />}
    />
  );
}

// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
  { label: 'The Shawshank Redemption', year: 1994 },
  ...
];

How best can this be achieved?

CodePudding user response:

If you want to scroll to the option, you need to identify the equivalent element on the DOM tree, then call Element.scrollIntoView().

You can do that by attaching a data attribute to each option element using renderOption, then every time the user opens, use document.querySelector() to find the option based on the attribute and scroll to it:

<Autocomplete
  onOpen={() => {
    setTimeout(() => {
      const optionEl = document.querySelector(
        `[data-name="${movieToScrollTo}"]`
      );
      optionEl?.scrollIntoView();
    }, 1);
  }}
  renderOption={(props, option) => {
    return (
      <li {...props} data-name={option.label}>
        {option.label}
      </li>
    );
  }}
/>

Live Demo

Codesandbox Demo

  • Related