How To

Configure the cascading DropDownList

The cascading DropDownList is a series of DropDownList, where the value of one DropDownList depends upon another’s value. This can be configured by using the change event of the parent DropDownList. Within that change event handler, data has to be loaded to the child DropDownList based on the selected value of the parent DropDownList.

The following example, shows the cascade behavior of country, state, and city DropDownList. Here, the dataBind method is used to reflect the property changes immediately to the DropDownList.

Source
Preview
index.tsx
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { DropDownListComponent, DropDownList } from '@syncfusion/ej2-react-dropdowns';
import { Query } from '@syncfusion/ej2-data';

export default class App extends React.Component<{}, {}> {
    constructor(){
        super();
        this.onCountryChange=this.onCountryChange.bind(this);
        this.onStateChange=this.onStateChange.bind(this);
    }
    // country DropDownList instance
    private countryObj: DropDownList;

    // state DropDownList instance
    private stateObj: DropDownList;

    // city DropDownList instance
    private cityObj: DropDownList;

    //define the country DropDownList data
    private countryData: { [key: string]: Object }[] = [
        { CountryName: 'Australia', CountryId: '2' },
        { CountryName: 'United States', CountryId: '1' }
    ];

    //define the state DropDownList data
    private stateData: { [key: string]: Object }[] = [
        { StateName: 'New York', CountryId: '1', StateId: '101' },
        { StateName: 'Virginia ', CountryId: '1', StateId: '102' },
        { StateName: 'Tasmania ', CountryId: '2', StateId: '105' }
    ];

    //define the city DropDownList data
    private cityData: { [key: string]: Object }[] = [
        { CityName: 'Albany', StateId: '101', CityId: 201 },
        { CityName: 'Beacon ', StateId: '101', CityId: 202 },
        { CityName: 'Emporia', StateId: '102', CityId: 206 },
        { CityName: 'Hampton ', StateId: '102', CityId: 205 },
        { CityName: 'Hobart', StateId: '105', CityId: 213 },
        { CityName: 'Launceston ', StateId: '105', CityId: 214 }
    ];

    // maps the country column to fields property
    private countryField: object = { value: 'CountryId', text: 'CountryName' };

    // maps the state column to fields property
    private stateField: object = { value: 'StateId', text: 'StateName' };

    // maps the city column to fields property
    private cityField: object = { text: 'CityName', value: 'CityId' };

    onCountryChange() {
        // query the data source based on country DropDownList selected value
        this.stateObj.query = new Query().where('CountryId', 'equal', this.countryObj.value);
        // enable the state DropDownList
        this.stateObj.enabled = true;
        // clear the existing selection.
        this.stateObj.text = null;
        // bind the property changes to state DropDownList
        this.stateObj.dataBind();
        // clear the existing selection in city DropDownList
        this.cityObj.text = null;
        // disable the city DropDownList
        this.cityObj.enabled = false;
        // bind the property change to City DropDownList
        this.cityObj.dataBind();
    }
    onStateChange() {
        // query the data source based on state DropDownList selected value
        this.cityObj.query = new Query().where('StateId', 'equal', this.stateObj.value);
        // enable the city DropDownList
        this.cityObj.enabled = true;
        //clear the existing selection
        this.cityObj.text = null;
        // bind the property change to city DropDownList
        this.cityObj.dataBind();
    }

    render() {
        return (
            <div>
                {/* specifies the tag for render the country DropDownList component */}
                <DropDownListComponent id="country-ddl" ref={(scope) => { this.countryObj = scope; }} fields={this.countryField} dataSource={this.countryData} placeholder='Select a country' change={this.onCountryChange} />
                <br />

                 {/* specifies the tag for render the state DropDownList component */}
                 <DropDownListComponent id="state-ddl" ref={(scope) => { this.stateObj = scope; }} enabled={false} fields={this.stateField} dataSource={this.stateData} placeholder='Select a state' change={this.onStateChange} />
                <br />

                 {/* specifies the tag for render the city DropDownList component */}
                <DropDownListComponent id="city-ddl" ref={(scope) => { this.cityObj = scope; }} enabled={false} fields={this.cityField} dataSource={this.cityData} placeholder='Select a city' />
            </div>
        );
    }
}
ReactDOM.render(<App />, document.getElementById('sample'));

Show the list items with icons

You can render icons to the list items by mapping the iconCss  field. This iconCss field create a span in the list item with mapped class name to allow styling as per your need.

In the following sample, icon classes are mapped with iconCss field.

Source
Preview
index.tsx
index.html
styles.css
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { DropDownListComponent } from '@syncfusion/ej2-react-dropdowns';

export default class App extends React.Component<{}, {}> {
    // define the array of data
    private sortFormatData: { [key: string]: Object }[] = [
        { Class: 'asc-sort', Type: 'Sort A to Z', Id: '1' },
        { Class: 'dsc-sort', Type: 'Sort Z to A ', Id: '2' },
        { Class: 'filter', Type: 'Filter', Id: '3' },
        { Class: 'clear', Type: 'Clear', Id: '4' }
    ];

    // map the icon column to iconCSS field.
    private fields: object = { text: 'Type', iconCss: 'Class', value: 'Id' };

    render() {
        return (
             // specifies the tag for render the DropDownList component
            <DropDownListComponent id="ddlelement" dataSource={this.sortFormatData} fields={this.fields} placeholder="Select a format" />
        );
    }
}
ReactDOM.render(<App />, document.getElementById('sample'));
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Syncfusion React DropDownList</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Essential JS 2 for React Components" />
    <meta name="author" content="Syncfusion" />
    <link href="//cdn.syncfusion.com/ej2/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-inputs/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-dropdowns/styles/material.css" rel="stylesheet" />
    <link href="./styles.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
    <style>
        #loader {
            color: #008cff;
            height: 40px;
            left: 45%;
            position: absolute;
            top: 45%;
            width: 30%;
        }
    </style>
</head>

<body>
    <div id='sample' style="width:250px; margin: 20px auto 0;">
        <div id='loader'>Loading....</div>
    </div>
</body>

</html>
.e-list-icon {
    line-height: 1.3;
    padding-right: 10px;
    text-indent: 5px;
}

.asc-sort:before {
    content: '\e73f';
    font-family: 'e-icons';
    font-size: 20px;
}

.dsc-sort:before {
    content: '\e721';
    font-family: 'e-icons';
    font-size: 20px;
}

.filter:before {
    content: '\e818';
    font-family: 'e-icons';
    font-size: 20px;
    opacity: 0.78;
}

.clear:before {
    content: '\e7db';
    font-family: 'e-icons';
    font-size: 20px;
}

Do incremental search in the DropDownList

DropDownList supports incremental search, by default. You can search the list item by focusing the DropDownList and typing the characters in it. The closely matched items are selected sequentially.

If the same key is searched once again, the next matched item is selected.

You can achieve this behavior by using ej2-tooltip component. When the mouse hover on the DropDownList option that tooltip display some details related to hovered list item.

Source
Preview
index.tsx
index.html
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { DropDownListComponent } from '@syncfusion/ej2-react-dropdowns';
import { Tooltip } from '@syncfusion/ej2-popups';

export default class App extends React.Component<{}, {}> {
    constructor(){
        super();
        this.onBeforeRender=this.onBeforeRender.bind(this);
        this.onClose=this.onClose.bind(this);
    }
     // define the JSON of data
    private countryData: { [key: string]: Object }[] = [
         { id: '1', text: 'Australia', content: 'National sports is Cricket' },
        { id: '2', text: 'Bhutan', content: 'National sports is Archery' },
        { id: '3', text: 'China', content: 'National sports is Table Tennis' },
        { id: '4', text: 'Cuba', content: 'National sports is Baseball' },
        { id: '5', text: 'India', content: 'National sports is Hockey' },
        { id: '6', text: 'Spain', content: 'National sports is Football' },
        { id: '7', text: 'United States', content: 'National sports is Baseball' }
    ];

    // maps the appropriate column to fields property
    private fields: object = { text: 'text', value: 'id' };
    private tooltip: TooltipComponent;
    private dropDownListObject:DropDownList;
    onBeforeRender(args){
    // get the target element
    let result = this.dropDownListObject.dataSource;
    let i;
    for (i = 0; i < result.length; i++) {
        if (result[i].text === args.target.textContent) {
            this.tooltip.content = result[i].content;
            this.tooltip.dataBind();
            break;
        }
    }
   }
   onClose(){
   this.tooltip.close();
   }
   componentDidMount(){
        this.tooltip = new Tooltip({
            // default content of tooltip
            content: 'Loading...',
            // set target element to tooltip
            target: '.e-list-item',
            // set position of tooltip
            position: 'top center',
            // bind beforeRender event
            beforeRender: this.onBeforeRender
        });

        this.tooltip.appendTo('body');
    }
    render() {
        return (

             // specifies the tag for render the DropDownList component
             // specifies the tag for render the DropDownList component
            <DropDownListComponent id="ddlelement" ref={(scope) => { this.dropDownListObject = scope; }} dataSource={this.countryData} fields={this.fields} placeholder="Select a country" close={this.onClose} />
        );
    }
}
ReactDOM.render(<App />, document.getElementById('sample'));
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Syncfusion React DropDownList</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Essential JS 2 for React Components" />
    <meta name="author" content="Syncfusion" />
    <link href="//cdn.syncfusion.com/ej2/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-inputs/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-dropdowns/styles/material.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
    <style>
        #loader {
            color: #008cff;
            height: 40px;
            left: 45%;
            position: absolute;
            top: 45%;
            width: 30%;
        }
    </style>
</head>

<body>
    <div id='sample' style="margin: 20px auto 0; width:250px;">
        <div id='loader'>Loading....</div>
    </div>
</body>

</html>

Close the popup on scroll

By using the hidePopup method in DropDownList, you can close the popup on scroll when triggered the windows scroll event.

The following example demonstrate about how to close the popup on scroll.

Source
Preview
index.tsx
index.html
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { DropDownListComponent } from '@syncfusion/ej2-react-dropdowns';

export default class App extends React.Component<{}, {}> {
    constructor(){
        super();
       window.addEventListener('scroll', this.handleScroll.bind(this));
    }
    private dropDownListObject:DropDownList;
    //define the data with category
    private sportsData: { [key: string]: Object }[] = [
      'Badminton', 'Cricket', 'Football', 'Golf', 'Tennis' ];
    //on scroll event
    handleScroll(){
        this.dropDownListObject.hidePopup();
    }
    render() {
        return (

             // specifies the tag for render the DropDownList component
            <DropDownListComponent id="ddlelement" ref={(scope) => { this.dropDownListObject = scope; }}  dataSource={this.sportsData} placeholder="Select a game" />
        );
    }
}
ReactDOM.render(<App />, document.getElementById('sample'));
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Syncfusion React DropDownList</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Essential JS 2 for React Components" />
    <meta name="author" content="Syncfusion" />
    <link href="//cdn.syncfusion.com/ej2/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-inputs/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-dropdowns/styles/material.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
    <style>
        #loader {
            color: #008cff;
            height: 40px;
            left: 45%;
            position: absolute;
            top: 45%;
            width: 30%;
        }
    </style>
</head>

<body>
    <div id='sample' style="margin: 20px auto 0; width:250px;">
        <div id='loader'>Loading....</div>
    </div>
</body>

</html>

Whether each list items hold unique value

yes, value for each list items should be unique.

Clear the selected item in DropDownList

You can clear the selected item in the below two different ways.

By clicking on the clear icon which is shown in DropDownList element, you can clear the selected item in DropDownList through interaction. By using showClearButton property, you can enable the clear icon in DropDownList element.

Through programmatic you can set null value to anyone of the index, text or value property to clear the selected item in DropDownList.

The following example demonstrate about how to clear the selected item in DropDownList.

Source
Preview
index.tsx
index.html
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { DropDownListComponent } from '@syncfusion/ej2-react-dropdowns';

export default class App extends React.Component<{}, {}> {
private dropDownListObject:DropDownList;
private sportsData: string[] = ['Badminton', 'Cricket', 'Football', 'Golf', 'Tennis'];
onclick(){
this.dropDownListObject.value = null;
}
render() {
    return (
        // specifies the tag for render the DropDownList component
        <div>
      <DropDownListComponent id="ddlelement" ref={(scope) => { this.dropDownListObject = scope; }} dataSource={this.sportsData}  placeholder="Select a game" />
           <button id='btn' className="e-control e-btn" onClick={() => this.onclick()}> Set null to value property</button>
     </div>
    );
  }
}
ReactDOM.render(<App />, document.getElementById('sample'));
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Syncfusion React DropDownList</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Essential JS 2 for React Components" />
    <meta name="author" content="Syncfusion" />
    <link href="//cdn.syncfusion.com/ej2/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-inputs/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-dropdowns/styles/material.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
    <style>
        #loader {
            color: #008cff;
            height: 40px;
            left: 45%;
            position: absolute;
            top: 45%;
            width: 30%;
        }
    </style>
</head>

<body>
    <div id='sample' style="margin: 20px auto 0; width:250px;">
        <div id='loader'>Loading....</div>
    </div>
</body>

</html>

Preselect the list items in multiple cascading DropDownList

The following example demonstrate about how to preselect the list items in multiple cascading DropDownList.

Source
Preview
index.tsx
index.html
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { DropDownListComponent, DropDownList } from '@syncfusion/ej2-react-dropdowns';
import { Query } from '@syncfusion/ej2-data';

export default class App extends React.Component<{}, {}> {
    constructor(){
        super();
        this.onCountryChange=this.onCountryChange.bind(this);
        this.onStateChange=this.onStateChange.bind(this);
    }
    // country DropDownList instance
    private countryObj: DropDownList;

    // state DropDownList instance
    private stateObj: DropDownList;

    // city DropDownList instance
    private cityObj: DropDownList;

    //define the country DropDownList data
    private countryData: { [key: string]: Object }[] = [
        { CountryName: 'Australia', CountryId: '2' },
        { CountryName: 'United States', CountryId: '1' }
    ];

    //define the state DropDownList data
    private stateData: { [key: string]: Object }[] = [
        { StateName: 'New York', CountryId: '1', StateId: '101' },
        { StateName: 'Virginia ', CountryId: '1', StateId: '102' },
        { StateName: 'Tasmania ', CountryId: '2', StateId: '105' }
    ];

    //define the city DropDownList data
    private cityData: { [key: string]: Object }[] = [
        { CityName: 'Albany', StateId: '101', CityId: 201 },
        { CityName: 'Beacon ', StateId: '101', CityId: 202 },
        { CityName: 'Emporia', StateId: '102', CityId: 206 },
        { CityName: 'Hampton ', StateId: '102', CityId: 205 },
        { CityName: 'Hobart', StateId: '105', CityId: 213 },
        { CityName: 'Launceston ', StateId: '105', CityId: 214 }
    ];

    // maps the country column to fields property
    private countryField: object = { value: 'CountryId', text: 'CountryName' };

    // maps the state column to fields property
    private stateField: object = { value: 'StateId', text: 'StateName' };

    // maps the city column to fields property
    private cityField: object = { text: 'CityName', value: 'CityId' };

    // Index no of the country dropdownlist
    private index: number = 1;

    onCountryChange() {
        // query the data source based on country DropDownList selected value
        this.stateObj.query = new Query().where('CountryId', 'equal', this.countryObj.value);
        // enable the state DropDownList
        this.stateObj.enabled = true;
        // clear the existing selection.
        this.stateObj.text = null;
        // bind the property changes to state DropDownList
        this.stateObj.dataBind();
        // clear the existing selection in city DropDownList
        this.cityObj.text = null;
        // disable the city DropDownList
        this.cityObj.enabled = false;
        // bind the property change to City DropDownList
        this.cityObj.dataBind();
    }
    onStateChange() {
        // query the data source based on state DropDownList selected value
        this.cityObj.query = new Query().where('StateId', 'equal', this.stateObj.value);
        // enable the city DropDownList
        this.cityObj.enabled = true;
        //clear the existing selection
        this.cityObj.text = null;
        // bind the property change to city DropDownList
        this.cityObj.dataBind();
    }
     componentDidMount(){
        this.onCountryChange();
        // preselect an item from filtered state DropDownList
        this.stateObj.index = 0;
        this.stateObj.dataBind();
        // initally change event not triggered, so manually call the corresponding function
        this.onStateChange();
        // preselect an item from filtered city DropDownList
        this.cityObj.index = 0;
        this.cityObj.dataBind();
    }
    render() {
        return (
            <div>
                {/* specifies the tag for render the country DropDownList component */}
                <DropDownListComponent id="country-ddl" ref={(scope) => { this.countryObj = scope; }} index={this.index} fields={this.countryField} dataSource={this.countryData} placeholder='Select a country' change={this.onCountryChange} />
                <br />

                 {/* specifies the tag for render the state DropDownList component */}
                 <DropDownListComponent id="state-ddl" ref={(scope) => { this.stateObj = scope; }} enabled={false} fields={this.stateField} dataSource={this.stateData} placeholder='Select a state' change={this.onStateChange} />
                <br />

                 {/* specifies the tag for render the city DropDownList component */}
                <DropDownListComponent id="city-ddl" ref={(scope) => { this.cityObj = scope; }} enabled={false} fields={this.cityField} dataSource={this.cityData} placeholder='Select a city' />
            </div>
        );
    }
}
ReactDOM.render(<App />, document.getElementById('sample'));
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Syncfusion React DropDownList</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Essential JS 2 for React Components" />
    <meta name="author" content="Syncfusion" />
    <link href="//cdn.syncfusion.com/ej2/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-inputs/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-dropdowns/styles/material.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
    <style>
        #loader {
            color: #008cff;
            height: 40px;
            left: 45%;
            position: absolute;
            top: 45%;
            width: 30%;
        }
    </style>
</head>

<body>
    <div id='sample' style="margin: 20px auto 0; width:250px;">
        <div id='loader'>Loading....</div>
    </div>
</body>

</html>

Disable the Fixed group header in DropDownList

The following example demonstrate about how to disable the Fixed group header in DropDownList through CSS by using visibility attribute.

Source
Preview
index.tsx
index.html
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { DropDownListComponent } from '@syncfusion/ej2-react-dropdowns';

export default class App extends React.Component<{}, {}> {
    //define the data with category
    private vegetableData: { [key: string]: Object }[] = [
        { Vegetable: 'Cabbage', Category: 'Leafy and Salad', Id: 'item1' },
        { Vegetable: 'Spinach', Category: 'Leafy and Salad', Id: 'item2' },
        { Vegetable: 'Wheat grass', Category: 'Leafy and Salad', Id: 'item3' },
        { Vegetable: 'Yarrow', Category: 'Leafy and Salad', Id: 'item4' },
        { Vegetable: 'Pumpkins', Category: 'Leafy and Salad', Id: 'item5' },
        { Vegetable: 'Chickpea', Category: 'Beans', Id: 'item6' },
        { Vegetable: 'Green bean', Category: 'Beans', Id: 'item7' },
        { Vegetable: 'Horse gram', Category: 'Beans', Id: 'item8' },
        { Vegetable: 'Garlic', Category: 'Bulb and Stem', Id: 'item9' },
        { Vegetable: 'Nopal', Category: 'Bulb and Stem', Id: 'item10' },
        { Vegetable: 'Onion', Category: 'Bulb and Stem', Id: 'item11' }
    ];

    // map the groupBy field with Category column
    private fields: object = { groupBy: 'Category', text: 'Vegetable', value: 'Id' };

    render() {
        return (
             // specifies the tag for render the DropDownList component
            <DropDownListComponent id="ddlelement" popupHeight='200px' fields={this.fields} dataSource={this.vegetableData} placeholder="Select a vegetable" />
        );
    }
}
ReactDOM.render(<App />, document.getElementById('sample'));
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Syncfusion React DropDownList</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Essential JS 2 for React Components" />
    <meta name="author" content="Syncfusion" />
    <link href="//cdn.syncfusion.com/ej2/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-inputs/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-dropdowns/styles/material.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
    <style>
        #loader {
            color: #008cff;
            height: 40px;
            left: 45%;
            position: absolute;
            top: 45%;
            width: 30%;
        }
		.e-ddl .e-dropdownbase .e-fixed-head {
            visibility: hidden;
        }
    </style>
</head>

<body>
    <div id='sample' style="margin: 20px auto 0; width:250px;">
        <div id='loader'>Loading....</div>
    </div>
</body>

</html>

Detect whether the value change happened by manual or programmatic

You can check about whether value change happened by manual or programmatic by using change event argument that argument name is isInteracted.

The following example demonstrate, how to check whether value change happened by manual or programmatic.

Source
Preview
index.tsx
index.html
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { DropDownListComponent } from '@syncfusion/ej2-react-dropdowns';
export default class App extends React.Component<{}, {}> {
  // define the array of data
  private sportsData: string[] = ['Badminton', 'Cricket', 'Football', 'Golf', 'Tennis'];
  private dropDownListObject:DropDownList;
    onclick(){
        this.dropDownListObject.value = 'Football';
        }
    onChange(args){
    let element: HTMLElement = document.createElement('p');
        if (args.isInteracted) {
            element.innerText = 'Changes happened by Interaction';
        } else {
            element.innerText = 'Changes happened by programmatic';
        }
        document.getElementById('event').append(element);
    }
  render() {
    return (
        // specifies the tag for render the DropDownList component
      <div>
      <DropDownListComponent id="ddlelement" ref={(scope) => { this.dropDownListObject = scope; }} dataSource={this.sportsData}  placeholder="Select a game" change={this.onChange} />
      <button id='btn' className="e-control e-btn" onClick={() => this.onclick()}>
      Set value dynamically</button>
      </div>
    );
  }
}
ReactDOM.render(<App />, document.getElementById('sample'));
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Syncfusion React DropDownList</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Essential JS 2 for React Components" />
    <meta name="author" content="Syncfusion" />
    <link href="//cdn.syncfusion.com/ej2/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-inputs/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-dropdowns/styles/material.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
    <style>
        #loader {
            color: #008cff;
            height: 40px;
            left: 45%;
            position: absolute;
            top: 45%;
            width: 30%;
        }
    </style>
</head>

<body>
    <div id='sample' style="margin: 20px auto 0; width:250px;">
        <div id='loader'>Loading....</div>
    </div>
	<p id='event'> </p>
</body>

</html>

Add item in between in DropDownList

You can add item in between based on item index. If you add new item without item index, item will be added as last item in list.

The following example demonstrate how to add item in between in DropDownList.

Source
Preview
index.tsx
index.html
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { DropDownListComponent } from '@syncfusion/ej2-react-dropdowns';

export default class App extends React.Component<{}, {}> {

    // define the JSON of data
    private sportsData: { [key: string]: Object }[] = [
        { Id: 'game1', Game: 'Badminton' },
        { Id: 'game2', Game: 'Football' },
        { Id: 'game3', Game: 'Tennis' }
    ];
    private dropDownListObject:DropDownList;
    // maps the appropriate column to fields property
    private fields: object = { text: 'Game', value: 'Id' };
    onclickfirst(){
    this.dropDownListObject.addItem({Id: 'game0', Game: 'Hockey'}, 0);
    }
    onclick(){
    this.dropDownListObject.addItem({Id: 'game4', Game: 'Golf'}, 2);
    }
    onclicklast(){
    this.dropDownListObject.addItem({Id: 'game5', Game: 'Cricket'});
    }
    render() {
        return (
             // specifies the tag for render the DropDownList component
            <div>
                <DropDownListComponent id="ddlelement" ref={(scope) => { this.dropDownListObject = scope; }}dataSource={this.sportsData} fields={this.fields} placeholder="Select a game" />
                <div id="btn1Div">
                <button id='btn' className="e-control e-btn" onClick={() => this.onclickfirst()}>
                add item (Hockey) in first</button>
            </div>
            <div id="btn2Div">
                <button id='btn2' className="e-control e-btn" onClick={() => this.onclick()}> add item (Golf) in between</button>
            </div>
            <div id="btn3Div">
                <button id='btn3' className="e-control e-btn" onClick={() => this.onclicklast()}>
                  add item (Cricket) in last</button>
            </div>
            </div>
        );
    }
}
ReactDOM.render(<App />, document.getElementById('sample'));
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Syncfusion React DropDownList</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Essential JS 2 for React Components" />
    <meta name="author" content="Syncfusion" />
    <link href="//cdn.syncfusion.com/ej2/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-inputs/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-dropdowns/styles/material.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
    <style>
        #loader {
            color: #008cff;
            height: 40px;
            left: 45%;
            position: absolute;
            top: 45%;
            width: 30%;
        }
		 #btn1Div{
        padding: 50px 0;
          
        }
        #btn2Div{
       padding-left: 50px 0;
          
        }
        #btn3Div{
        padding: 50px 0;
          
        }
    </style>
</head>

<body>
    <div id='sample' style="margin: 20px auto 0; width:250px;">
        <div id='loader'>Loading....</div>
    </div>
</body>

</html>

Remove an item from DropDownList

The following example demonstrate about how to remove an item from DropDownList.

Source
Preview
index.tsx
index.html
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { DropDownListComponent } from '@syncfusion/ej2-react-dropdowns';

export default class App extends React.Component<{}, {}> {
  // define the array of data
   private sportsData: { [key: string]: Object }[] = [
        { Id: 'game1', Game: 'Badminton' },
        { Id: 'game2', Game: 'Football' },
        { Id: 'game3', Game: 'Tennis' }
    ];

    // maps the appropriate column to fields property
    private fields: object = { text: 'Game', value: 'Id' };
    private dropDownListObject:DropDownList;
    onclick(){
         let obj: any = document.getElementById('ddlelement');
         if (obj.ej2_instances[0].list) {
            // Remove the selected value if 0th index selected
          if (this.dropDownListObject.index === 0) {
             this.dropDownListObject.value = null;
             this.dropDownListObject.dataBind();
          }
            // remove first item in list
          (obj.ej2_instances[0].list.querySelectorAll('li')[0]).remove();
          if (!obj.ej2_instances[0].list.querySelectorAll('li')[0]) {
                this.dropDownListObject.dataSource = [];
                // enable the nodata template when no data source is empty.
                obj.ej2_instances[0].list.classList.add('e-nodata');
           }
           } else {
            // remove first item in list
            this.dropDownListObject.dataSource.splice(0, 1);
           }

    }
    render() {
        return (
             // specifies the tag for render the DropDownList component
             <div>
            <DropDownListComponent id="ddlelement" ref={(scope) => { this.dropDownListObject = scope; }} dataSource={this.sportsData} fields={this.fields} placeholder="Select a game" />
            <button id='btn' className="e-control e-btn" onClick={() => this.onclick()}>
            Remove 0th item </button>
      </div>
        );
  }
}
ReactDOM.render(<App />, document.getElementById('sample'));
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Syncfusion React DropDownList</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Essential JS 2 for React Components" />
    <meta name="author" content="Syncfusion" />
    <link href="//cdn.syncfusion.com/ej2/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-inputs/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-dropdowns/styles/material.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
    <style>
        #loader {
            color: #008cff;
            height: 40px;
            left: 45%;
            position: absolute;
            top: 45%;
            width: 30%;
        }
    </style>
</head>

<body>
    <div id='sample' style="margin: 20px auto 0; width:250px;">
        <div id='loader'>Loading....</div>
    </div>
</body>

</html>

Modify the result data before passing to DropDownList when binding remote data source

When binding the remote data source, by using the actionComplete event, you can modify the result data before passing it to DropDownList.

The following sample demonstrate how to modify the result data.

Source
Preview
index.tsx
index.html
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { DropDownListComponent } from '@syncfusion/ej2-react-dropdowns';
//import DataManager related classes
import { Query, DataManager, ODataV4Adaptor } from '@syncfusion/ej2-data';

export default class App extends React.Component<{}, {}> {
    // bind the DataManager instance to dataSource property
    private customerData: DataManager = new DataManager({
        url: 'http://services.odata.org/V4/Northwind/Northwind.svc/',
        adaptor: new ODataV4Adaptor,
        crossDomain: true
    });
    // bind the Query instance to query property
    private query: Query = new Query().from('Customers').select(['ContactName', 'CustomerID']).take(6);
    // maps the appropriate column to fields property
    private fields: object = { text: 'ContactName', value: 'CustomerID' };
    //sort the resulted items
    private sortOrder: string = 'Ascending';
    onComplete(e){
    // initially result contains 6 items
        console.log("Before modified the result: " + e.result.length);
        // remove first 2 items from result.
        e.result.splice(0, 2);
        // now displays the result count is 4.
        console.log("After modified the result: " + e.result.length);
    }
    render() {
        return (
              // specifies the tag for render the DropDownList component
            <DropDownListComponent id="ddlelement" query={this.query} dataSource={this.customerData}
            fields={this.fields} sortOrder={this.sortOrder} placeholder="Select a customer" actionComplete={this.onComplete} />
        );
    }
}
ReactDOM.render(<App />, document.getElementById('sample'));
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Syncfusion React DropDownList</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Essential JS 2 for React Components" />
    <meta name="author" content="Syncfusion" />
    <link href="//cdn.syncfusion.com/ej2/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-inputs/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-dropdowns/styles/material.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
    <style>
        #loader {
            color: #008cff;
            height: 40px;
            left: 45%;
            position: absolute;
            top: 45%;
            width: 30%;
        }
    </style>
</head>

<body>
    <div id='sample' style="margin: 20px auto 0; width:250px;">
        <div id='loader'>Loading....</div>
    </div>
</body>

</html>

Get the total count of data when remote data bind with DropDownList

Before component rendering, you can get the total items count by using actionComplete  event with its result arguments.

After rendering this component, you can get the total items count by using getItems method.

The following example demonstrate how to get the total items count.

Source
Preview
index.tsx
index.html
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { DropDownListComponent } from '@syncfusion/ej2-react-dropdowns';
//import DataManager related classes
import { Query, DataManager, ODataV4Adaptor } from '@syncfusion/ej2-data';

export default class App extends React.Component<{}, {}> {
    constructor(){
        super();
        this.onclick=this.onclick.bind(this);
    }
    // bind the DataManager instance to dataSource property
    private customerData: DataManager = new DataManager({
        url: 'http://services.odata.org/V4/Northwind/Northwind.svc/',
        adaptor: new ODataV4Adaptor,
        crossDomain: true
    });
    private dropDownListObject:DropDownList;
    // bind the Query instance to query property
    private query: Query = new Query().from('Customers').select(['ContactName', 'CustomerID']).take(6);
    // maps the appropriate column to fields property
    private fields: object = { text: 'ContactName', value: 'CustomerID' };
    //sort the resulted items
    private sortOrder: string = 'Ascending';
     onActionComplete(e){
         // get total items count
        console.log("Total items count: " + e.result.length);
        let element: HTMLElement = document.createElement('p');
        element.innerText = "Total items count: " + e.result.length;
        document.getElementById('event').append(element);
    }
    onclick(){
    // get items count using getItems method
    console.log("Total items count: " + this.dropDownListObject.listData.length);
    let element: HTMLElement = document.createElement('p');
    element.innerText = "Total items count: " + this.dropDownListObject.listData.length;
    document.getElementById('event').append(element);
    }
    render() {
        return (
              // specifies the tag for render the DropDownList component
              <div>
             <DropDownListComponent ref={(scope) => { this.dropDownListObject = scope; }} id="ddlelement"
              query={this.query} dataSource={this.customerData}
            fields={this.fields} sortOrder={this.sortOrder} placeholder="Select a customer" actionComplete={this.onActionComplete} />
            <button id='btn' className="e-control e-btn" onClick={ this.onclick}> Get items </button>
            </div>
        );
    }
}
ReactDOM.render(<App />, document.getElementById('sample'));
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Syncfusion React DropDownList</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Essential JS 2 for React Components" />
    <meta name="author" content="Syncfusion" />
    <link href="//cdn.syncfusion.com/ej2/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-inputs/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-dropdowns/styles/material.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
    <style>
        #loader {
            color: #008cff;
            height: 40px;
            left: 45%;
            position: absolute;
            top: 45%;
            width: 30%;
        }
		#btn{
			margin: 50px;
		}
    </style>
</head>

<body>
    <div id='sample' style="margin: 20px auto 0; width:250px;">
        <div id='loader'>Loading....</div>
    </div>
	<div id='event'></div>
</body>

</html>

Limit the search result on filtering

The following example demonstrates about how to set limit the search result on filtering.

Source
Preview
index.tsx
index.html
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { DropDownListComponent, FilteringEventArgs } from '@syncfusion/ej2-react-dropdowns';
import { Query, DataManager, ODataV4Adaptor } from '@syncfusion/ej2-data';

export default class App extends React.Component<{}, {}> {
    constructor() {
        super();
        this.onFiltering = this.onFiltering.bind(this);
    }
    // bind the DataManager instance to dataSource property
    private searchData: DataManager = new DataManager({
        url: 'http://services.odata.org/V4/Northwind/Northwind.svc/Customers',
        adaptor: new ODataV4Adaptor,
        crossDomain: true
    });
    // maps the appropriate column to fields property
    private fields: object = { text: 'ContactName', value: 'CustomerID' };
    // bind the Query instance to query property
    private query: Query = new Query().select(['ContactName', 'CustomerID']).take(7);
    //sort the resulted items
    private sortOrder: string = 'Ascending';
     // filtering event handler to filter a customer
    onFiltering(e: FilteringEventArgs) {
        // set limit as 4 to search result
        let query: Query = new Query().select(['ContactName', 'CustomerID']).take(4);
        query = (e.text !== '') ? query.where('ContactName', 'startswith', e.text, true) : query;
        e.updateData(this.searchData, query);
    }

    render() {
        return (
             // specifies the tag for render the DropDownList component
            <DropDownListComponent id="ddlelement" allowFiltering={true} popupHeight="250px" filtering={this.onFiltering} sortOrder={this.sortOrder} query={this.query} dataSource={this.searchData} fields={this.fields} placeholder="Select a customer" />
        );
    }
}
ReactDOM.render(<App />, document.getElementById('sample'));
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Syncfusion React DropDownList</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Essential JS 2 for React Components" />
    <meta name="author" content="Syncfusion" />
    <link href="//cdn.syncfusion.com/ej2/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-inputs/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-dropdowns/styles/material.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
    <style>
        #loader {
            color: #008cff;
            height: 40px;
            left: 45%;
            position: absolute;
            top: 45%;
            width: 30%;
        }
    </style>
</head>

<body>
    <div id='sample' style="margin: 20px auto 0; width:250px;">
        <div id='loader'>Loading....</div>
    </div>
</body>

</html>

Highlight the matched character in filtering

By using the highlightSearch method, you can highlight the matched character in DropDownList filtering.

The following example demonstrates about how to highlight the matched character in filtering.

Source
Preview
index.tsx
index.html
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { DropDownListComponent, FilteringEventArgs, highlightSearch } from '@syncfusion/ej2-react-dropdowns';
import { Query, DataManager, ODataV4Adaptor } from '@syncfusion/ej2-data';

export default class App extends React.Component<{}, {}> {
  constructor() {
    super();
  }
  // bind the DataManager instance to dataSource property
  private searchData: DataManager = new DataManager({
    url: 'http://services.odata.org/V4/Northwind/Northwind.svc/Customers',
    adaptor: new ODataV4Adaptor,
    crossDomain: true
  });
  // maps the appropriate column to fields property
  private fields: object = {
    text: 'ContactName', value: 'CustomerID', itemCreated: this.onItemCreated.bind(this)
  };
  // bind the Query instance to query property
  private query: Query = new Query().select(['ContactName', 'CustomerID']).take(7);
  //sort the resulted items
  private sortOrder: string = 'Ascending';
  private queryString: string;
  // highlight the item
  onItemCreated(e: any) {
    highlightSearch(e.item, this.queryString, true, 'StartsWith');
  }
  // filtering event handler to filter a customer
  onFiltering(e: FilteringEventArgs) {
    // take text for highlight the character in list items.
    this.queryString = e.text;
    let query: Query = new Query().select(['ContactName', 'CustomerID']);
    //frame the query based on search string with filter type.
    query = (e.text !== '') ? query.where('ContactName', 'startswith', e.text, true) : query;
    //pass the filter data source, filter query to updateData method.
    e.updateData(this.searchData, query);
  }

  render() {
    return (
      // specifies the tag for render the DropDownList component
      <DropDownListComponent id="ddlelement" allowFiltering={true} popupHeight="250px" filtering={this.onFiltering.bind(this)} query={this.query} dataSource={this.searchData} fields={this.fields} placeholder="Select a customer" />
    );
  }
}
ReactDOM.render(<App />, document.getElementById('sample'));
<!DOCTYPE html>
<html lang="en">

<head>
    <title>Syncfusion React DropDownList</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Essential JS 2 for React Components" />
    <meta name="author" content="Syncfusion" />
    <link href="//cdn.syncfusion.com/ej2/ej2-base/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-inputs/styles/material.css" rel="stylesheet" />
    <link href="//cdn.syncfusion.com/ej2/ej2-react-dropdowns/styles/material.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
    <script src="systemjs.config.js"></script>
    <style>
        #loader {
            color: #008cff;
            height: 40px;
            left: 45%;
            position: absolute;
            top: 45%;
            width: 30%;
        }
    </style>
</head>

<body>
    <div id='sample' style="margin: 20px auto 0; width:250px;">
        <div id='loader'>Loading....</div>
    </div>
</body>

</html>