MultiSelect dropdown in React
Today we will show you how to create a multi-select dropdown in React. Here, we will use the react-select npm package to implement a multi-select dropdown in React JS.
Checkout more articles on ReactJS
Demo Application
Steps to implement multi-select dropdown
1. Install react-select package
Let’s create a react application using create-react-app
and install the react-select npm dependency by running the command.
1 | npm install react-select |
2. Add multi-select dropdown
We recommend that you check out the article below.
Use the isMulti
property to convert the dropdown into the multi-select dropdown.
1 2 3 4 5 6 7 | import Select from 'react-select'; ... ... <Select ... isMulti /> |
Let’s create an example where we can implement the multi-select dropdown. Check the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | import React, { useState } from 'react'; import Select from 'react-select'; function App() { const data = [ { value: 1, label: "cerulean" }, { value: 2, label: "fuchsia rose" }, { value: 3, label: "true red" }, { value: 4, label: "aqua sky" }, { value: 5, label: "tigerlily" }, { value: 6, label: "blue turquoise" } ]; const [selectedOption, setSelectedOption] = useState(null); // handle onChange event of the dropdown const handleChange = e => { setSelectedOption(e); } return ( <div className="App"> <b>MultiSelect Dropdown - <a href="https://www.cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></b><br /><br /> <Select isMulti placeholder="Select Option" value={selectedOption} // set selected value options={data} // set list of the data onChange={handleChange} // assign onChange function /> {selectedOption && <div style={{ marginTop: 20, lineHeight: '25px' }}> <b>Selected Options</b><br /> <pre>{JSON.stringify(selectedOption, null, 2)}</pre> </div>} </div> ); } export default App; |
3. Output
Run the application and check the output in the browser.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂