Virtualization in React AutoComplete

24 Sep 202622 minutes to read

React AutoComplete virtualization is a technique used to efficiently render extensive lists of items while minimizing the performance impact. This method is particularly advantageous when dealing with large datasets because it ensures that only a fixed number of DOM (Document Object Model) elements are created. When scrolling through the list, existing DOM elements are reused to display relevant data instead of generating new elements for each item. This recycling process is managed internally.

During virtual scrolling, the data retrieved from the data source depends on the popup height and the calculation of the list item height. Set enableVirtualization to true to activate virtualization. In addition, import the VirtualScroll module and register it using <Inject services={[VirtualScroll]} /> inside the component; virtualization only works when both enableVirtualization and the injected VirtualScroll service are present.

When fetching data from the data source, the actionBegin event is triggered before data retrieval begins. Then, the actionComplete event is triggered once the data is successfully fetched.

When the enableVirtualization property is enabled, the skip and take properties provided by the user within the Query class at the initial state or during the actionBegin or actionComplete events will not be considered. They are internally managed and calculated based on the popup height. To customize the number of items fetched per page, see Customizing items count in virtualization, where a user-provided take value greater than the minimum is honored.

Binding local data

The React AutoComplete can generate its list items through an array of complex objects. For this, the appropriate data fields should be mapped to the fields property. For background on field mapping, see Field mapping. When using virtual scrolling, the list updates based on the scroll offset value, triggering a request to fetch more data from the server. As the data is being fetched, the actionBegin event occurs before the data retrieval starts. Once the data retrieval is successful, the actionComplete event is triggered, indicating that the data fetch process is complete.

In the following example, the text field is mapped to the value field.

[Class Component]

import { AutoCompleteComponent, Inject, VirtualScroll } from '@syncfusion/ej2-react-dropdowns';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
export default class App extends React.Component {
    constructor(props) {
        super(props);
        this.records = Array.from({ length: 150 }, (_, i) => ({
            id: 'id' + (i + 1),
            text: `Item ${i + 1}`,
        }));
    }
    fields = { value: 'text' };
    render() {
        return (
            // specifies the tag for render the AutoComplete component
            <AutoCompleteComponent id="datas" dataSource={this.records} placeholder="e.g. Item 1" enableVirtualization={true} fields={this.fields} allowFiltering={true} popupHeight="200px">
                <Inject services={[VirtualScroll]} />
            </AutoCompleteComponent>);
    }
}
ReactDOM.render(<App />, document.getElementById('sample'));
import { AutoCompleteComponent, Inject, VirtualScroll } from '@syncfusion/ej2-react-dropdowns';
import * as React from 'react';
import * as ReactDOM from 'react-dom';

export default class App extends React.Component<{}, {}> {
  // maps the appropriate column to fields property
  private fields: object = { value: 'text' };

  // define the array of string
  private records: { [key: string]: Object }[] = [];

  constructor(props) {
    super(props);
    this.records = Array.from({ length: 150 }, (_, i) => ({
      id: 'id' + (i + 1),
      text: `Item ${i + 1}`,
    }));
  }
  public render() {
    return (
      // specifies the tag for render the AutoComplete component
      <AutoCompleteComponent id="datas" dataSource={this.records} placeholder="e.g. Item 1" enableVirtualization={true} fields={this.fields} allowFiltering={true} popupHeight="200px">
        <Inject services={[VirtualScroll]} />
      </AutoCompleteComponent>
    );
  }
}
ReactDOM.render(<App />, document.getElementById('sample'));

Binding remote data

The React AutoComplete supports retrieving data from remote data services with the help of the DataManager component, which triggers the actionBegin and actionComplete events and then updates the list data. During virtual scrolling, additional data is retrieved from the server, triggering the actionBegin and actionComplete events at that time as well. The following sample uses the WebApiAdaptor to fetch data from the remote endpoint.

The following sample displays the OrderID from the Orders data service.

[Class Component]

import { AutoCompleteComponent, Inject, VirtualScroll } from '@syncfusion/ej2-react-dropdowns';
import { DataManager, WebApiAdaptor , Query } from '@syncfusion/ej2-data';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
export default class App extends React.Component {
    customerData = new DataManager({
        url: 'https://services.syncfusion.com/react/production/api/Orders',
        adaptor: new WebApiAdaptor,
        crossDomain: true
    });
    customerField = { value: 'OrderID' };
    render() {
        return (
            // specifies the tag for render the AutoComplete component
            <AutoCompleteComponent id="datas" dataSource={this.customerData} placeholder="OrderID" enableVirtualization={true} fields={this.customerField} allowFiltering={true} popupHeight="200px">
                <Inject services={[VirtualScroll]} />
            </AutoCompleteComponent>);
    }
}
ReactDOM.render(<App />, document.getElementById('sample'));
import { AutoCompleteComponent, Inject, VirtualScroll } from '@syncfusion/ej2-react-dropdowns';
import { DataManager, WebApiAdaptor , Query } from '@syncfusion/ej2-data';
import * as React from 'react';
import * as ReactDOM from 'react-dom';

export default class App extends React.Component<{}, {}> {
  // maps the appropriate column to fields property
  private customerField: object = { value: 'OrderID' };
   
  private customerData: DataManager = new DataManager({
    url: 'https://services.syncfusion.com/react/production/api/Orders',
    adaptor: new WebApiAdaptor,
    crossDomain: true
  });

  public render() {
    return (
      // specifies the tag for render the AutoComplete component
      <AutoCompleteComponent id="datas" dataSource={this.customerData} placeholder="OrderID" enableVirtualization={true} fields={this.customerField} allowFiltering={true} popupHeight="200px">
        <Inject services={[VirtualScroll]} />
      </AutoCompleteComponent>
    );
  }
}
ReactDOM.render(<App />, document.getElementById('sample'));

Customizing items count in virtualization

When the enableVirtualization property is enabled, the take property provided by the user within the Query class at the initial state or during the actionBegin event will be considered. Internally, the component calculates the items that fit onto the current page (typically twice the popup’s height). If the provided take value is less than the minimum number of items that fit into the popup, it will not be considered.

The actionBegin event handler receives an ActionBeginEventArgs object whose query property exposes the current Query instance; you can assign a new Query (for example, args.query = new Query().take(45)) to override the page size.

The following sample demonstrates customizing the items count in virtualization.

[Class Component]

import { AutoCompleteComponent, Inject, VirtualScroll } from '@syncfusion/ej2-react-dropdowns';
import { Query } from '@syncfusion/ej2-data';

import * as React from 'react';
import * as ReactDOM from 'react-dom';
export default class App extends React.Component {
    // define the array of string
    constructor(props) {
        super(props);
        this.records = Array.from({ length: 150 }, (_, i) => ({
            id: 'id' + (i + 1),
            text: `Item ${i + 1}`,
        }));
    }
    fields = { value: 'text' };
    // bind the Query instance to query property
    query = new Query().take(40);

    Begin(args) {
        args.query = new Query().take(45);
    }

    render() {
        return (
            // specifies the tag for render the AutoComplete component
            <AutoCompleteComponent id="datas" dataSource={this.records} placeholder="e.g. Item 1" enableVirtualization={true} query={this.query} actionBegin={this.Begin} fields={this.fields} popupHeight="200px" >
                <Inject services={[VirtualScroll]} />
            </AutoCompleteComponent>);
    }
}
ReactDOM.render(<App />, document.getElementById('sample'));
import { AutoCompleteComponent, Inject, VirtualScroll } from '@syncfusion/ej2-react-dropdowns';
import { Query } from '@syncfusion/ej2-data';

import * as React from 'react';
import * as ReactDOM from 'react-dom';

export default class App extends React.Component<{}, {}> {
  // maps the appropriate column to fields property
  private fields: object = { value: 'text' };

   // define the array of string
   private records: { [key: string]: Object }[] = [];
   private query: Query = new Query().take(40);

    public Begin(e: any): void {
      e.query = new Query().take(45);
    }
   // define the array of string
   constructor(props) {
    super(props);
    this.records = Array.from({ length: 150 }, (_, i) => ({
        id: 'id' + (i + 1),
        text: `Item ${i + 1}`,
    }));
  }

  public render() {
    return (
      // specifies the tag for render the AutoComplete component
      <AutoCompleteComponent id="datas" dataSource={this.records} placeholder="e.g. Item 1" query={this.query} actionBegin={this.Begin} enableVirtualization={true} fields={this.fields} popupHeight="200px" >
      <Inject services={[VirtualScroll]}/>
  </AutoCompleteComponent>
    );
  }
}
ReactDOM.render(<App />, document.getElementById('sample'));

Grouping

The React AutoComplete component supports grouping with virtualization. It allows you to organize list items into groups based on different categories. Each item in the list can be classified using the groupBy field in the data source. After grouping, virtualization works similarly to local data binding. When the data source is bound to remote data, an initial request is made to retrieve all data for the purpose of grouping. Subsequently, the grouped data works in the same way as local data binding virtualization.

The following sample demonstrates grouping with virtualization.

[Class Component]

import { AutoCompleteComponent, Inject, VirtualScroll } from '@syncfusion/ej2-react-dropdowns';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
export default class App extends React.Component {
    constructor(props) {
        super(props);
        for (let i = 1; i <= 150; i++) {
            let item = {};
            item.id = 'id' + i;
            item.text = `Item ${i}`;
            // Generate a random number between 1 and 4 to determine the group
            const randomGroup = Math.floor(Math.random() * 4) + 1;
            switch (randomGroup) {
                case 1:
                    item.group = 'Group A';
                    break;
                case 2:
                    item.group = 'Group B';
                    break;
                case 3:
                    item.group = 'Group C';
                    break;
                case 4:
                    item.group = 'Group D';
                    break;
                default:
                    break;
            }
            this.records.push(item);
        }
    }
    fields = { groupBy: 'group', value: 'text' };
    render() {
        return (
            // specifies the tag for render the AutoComplete component
            <AutoCompleteComponent id="datas" dataSource={this.records} placeholder="e.g. Item 1" enableVirtualization={true} fields={this.fields} allowFiltering={true} popupHeight="200px">
                <Inject services={[VirtualScroll]} />
            </AutoCompleteComponent>);
    }
}
ReactDOM.render(<App />, document.getElementById('sample'));
import { AutoCompleteComponent, Inject, VirtualScroll } from '@syncfusion/ej2-react-dropdowns';
import * as React from 'react';
import * as ReactDOM from 'react-dom';

export default class App extends React.Component<{}, {}> {
  // maps the appropriate column to fields property
  private fields: object = { groupBy: 'group', value: 'text' };

  // define the array of string
  private records: { [key: string]: Object }[] = [];

  constructor(props) {
    super(props);
    for (let i = 1; i <= 150; i++) {
      const item: { id: string, text: string, group: string } = {
        id: 'id' + i,
        text: `Item ${i}`,
        group: ''
      };

      // Generate a random number between 1 and 4 to determine the group
      const randomGroup = Math.floor(Math.random() * 4) + 1;
      switch (randomGroup) {
        case 1:
          item.group = 'Group A';
          break;
        case 2:
          item.group = 'Group B';
          break;
        case 3:
          item.group = 'Group C';
          break;
        case 4:
          item.group = 'Group D';
          break;
        default:
          break;
      }
      this.records.push(item);
    }
  }
  public render() {
    return (
      // specifies the tag for render the AutoComplete component
      <AutoCompleteComponent id="datas" dataSource={this.records} placeholder="e.g. Item 1" enableVirtualization={true} fields={this.fields} allowFiltering={true} popupHeight="200px">
        <Inject services={[VirtualScroll]} />
      </AutoCompleteComponent>
    );
  }
}
ReactDOM.render(<App />, document.getElementById('sample'));