In this tutorial, you will learn how to use react-select
to create a multi-select dropdown component in a React js application.
React Dropdown Multi Select Example using React-select
Steps and how to create multi-select dropdown in react js app:
Step 1 – Create New React App
In this step, open your terminal and execute the following command on your terminal to create a new react app:
npx create-react-app my-react-app
To run the React app, execute the following command on your terminal:
npm start
Check out your React app on this URL: localhost:3000
Step 2 – Install React-Select and Bootstrap
In this step, execute the following command to install select and bootstrap 4 libraries into your react app:
npm install bootstrap --save npm install react-select
Add bootstrap.min.css file in src/App.js
file:
import React, { Component } from 'react' import '../node_modules/bootstrap/dist/css/bootstrap.min.css'; function App() { return ( <div> <h2>How to Create Multi-Select Dropdown in React Example</h2> </div> ); } export default App;
Step 3 – Creating the Multi-Select Dropdown Component
To create the multi-select dropdown component, we need to import the react-select
library in our component file and use its Select
component to render the dropdown.
First, let’s create a new file called MultiSelectDropdown.js
in the src
directory. In this file, we will define our component as follows:
import React, { useState } from 'react'; import Select from 'react-select'; const options = [ { value: 'apple', label: 'Apple' }, { value: 'banana', label: 'Banana' }, { value: 'orange', label: 'Orange' }, { value: 'pear', label: 'Pear' }, { value: 'grape', label: 'Grape' }, ]; const MultiSelectDropdown = () => { const [selectedOptions, setSelectedOptions] = useState([]); const handleMultiSelectChange = (selectedOptions) => { setSelectedOptions(selectedOptions); }; return ( <div> <Select options={options} isMulti onChange={handleMultiSelectChange} value={selectedOptions} /> </div> ); }; export default MultiSelectDropdown;
Step 4 – Using the Multi-Select Dropdown Component
Now that you have created our MultiSelectDropdown
component, we can use it in our React application.
In the App.js
file, we can import the MultiSelectDropdown
component and render it as follows:
import React from 'react'; import MultiSelectDropdown from './MultiSelectDropdown'; function App() { return ( <div className="App"> <h1>Multi-Select Dropdown Example</h1> <MultiSelectDropdown /> </div> ); } export default App;
Conclusion
In this tutorial, you have learned how to create a multi-select dropdown using the react-select
library in React.