Kay
Kay

Reputation: 19660

How to fix lag on select element containing a large list of options

I have a react application that uses react material ui, i am using the autocomplete react-select example which you can find here.

https://material-ui.com/components/autocomplete/

When the number of items in the select is large for example around 2500~ it lags and becomes unusable.

I have modified the original demo to make suggestions of length 2500 to populate the select.

const suggestions = [];
for (let i = 0; i < 2500; i = i + 1) {
  suggestions.push({ value: i, label: `Option ${i}` });
}

Please see the below demo example of my problem.

https://codesandbox.io/s/material-demo-vp59j

When you click the first selector it is very laggy.

Upvotes: 8

Views: 17491

Answers (3)

Smatchai J Yato
Smatchai J Yato

Reputation: 221

I used "filterOptions" to show first 500 items and other items still be matched when searched, like this.

  import Autocomplete, { createFilterOptions } from '@material-ui/lab/Autocomplete';

  const filterOptions = createFilterOptions({
    matchFrom: 'any',
    limit: 500,
  });
  
  <Autocomplete
    filterOptions={filterOptions}
  />

For more arguments. >> https://material-ui.com/components/autocomplete/#custom-filter

Upvotes: 22

Atul Rai
Atul Rai

Reputation: 171

I had same issue as I had to create a drop-down for around 3000 values. The trick is to show a limited items in the Autocomplete drop-down and let users search ones that cannot be found in the drop-down.

Use Filteroptions feature of material Ui Autocomplete and use a limit param and set it to say 200.

Autocomplete will show only 200 items in the drop-down and rest can be searched.

Upvotes: 4

Adeel Imran
Adeel Imran

Reputation: 13966

You should use react-window for this purpose. https://github.com/bvaughn/react-window

It is a library for efficiently rendering large lists and tabular data.

Here is a working demo with a lot records to show. It doesn't lag https://codesandbox.io/s/bvaughnreact-window-fixed-size-list-vertical-bbtz0

P.S: It is by one of the core guys on facebook react team.

Upvotes: 3

Related Questions