How To Add Multi Select Dropdown In React.js

Introduction

In this article, We will learn how to add multi select dropdown in React.js.

A React provides multi select functionality with various features like selection limit, CSS customization, checkbox, search option,
for accessibility and grouping features.it has behave like normal dropdown

How To Used

It’s main used for multiple filters could be selected at once.

Install Package

npm install multiselect-react-dropdown

Let’s understand with the following example.

Create new project in visual studio code and install the package.

Open App.js file and below code in it.

import logo from './logo.svg';
import './App.css';
import React, { useEffect, useState } from 'react'
import Multiselect from 'multiselect-react-dropdown';

function App() {
  const [optionData, setoptionData] = useState([])
  const onSelect = (selectedList, selectedItem) => {
    setoptionData(selectedList);
    let value = "";
    selectedList.forEach(element => {
      value = value == "" ? element.name : value + "," + element.name;
    });
    alert(value)
  }
  const onRemove = (selectedList, removedItem) => {
    setoptionData(selectedList);
    let value = "";
    selectedList.forEach(element => {
      value = value == "" ? element.name : value + "," + element.name;
    });
    alert(value)
  }

  const options = [
    { name: 'Option 1', id: 1 },
    { name: 'Option 2', id: 2 },
    { name: 'Option 3', id: 3 },
    { name: 'Option 4', id: 4 },
  ]
 
  return (
    <>
      <div className='row'>
        <div className='col-md-3'>
          <label><b>Options</b></label>
          <Multiselect
            options={options} // Options to display in the dropdown
            onSelect={onSelect} // Function will trigger on select event
            onRemove={onRemove} // Function will trigger on remove event
            displayValue="name" // Property name to display in the dropdown options
          />
        </div>
      </div>
    </>
  );
}

export default App;

after run the application and below output is appear.

Output :

How To Set Default Value Selected in Multi Select Dropdown

const selectedOptions = [
    { name: 'Option 1', id: 1 }
  ]

 <Multiselect
            options={options} // Options to display in the dropdown
            selectedValues={selectedOptions} // Preselected value to persist in dropdown
            onSelect={onSelect} // Function will trigger on select event
            onRemove={onRemove} // Function will trigger on remove event
            displayValue="name" // Property name to display in the dropdown options
          />

Thank you for watching. If you have any doubt please let me know.

Watch my previous blogs here.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories