React multi select listbox component
React multi select listbox component is nothing but a list of items where we can select multiple options from the list.
We have written an article to Implement dropdown in React using react-select NPM Package.
Steps to implement multi select listbox component
1. Create react application
Refer to the link below if you don’t know how to create a react app using create-react-app
.
How to create react application
2. Add listbox component
To create a listbox component, we’ll use the select
HTML tag with multiple
attribute. Check out the following code.
1 2 3 4 5 6 7 8 9 10 | <select name="list-box" multiple> <option value="Value 1">Option 1</option> <option value="Value 2">Option 2</option> <option value="Value 3">Option 3</option> <option value="Value 4">Option 4</option> <option value="Value 5">Option 5</option> <option value="Value 6">Option 6</option> <option value="Value 7">Option 7</option> <option value="Value 8">Option 8</option> </select> |
3. Implement onChange event
Let’s implement the onChange
event of the list box and manage the multi selected values in the state variable.
1 2 3 4 5 6 7 8 | const [selectedList, setSelectedList] = useState([]); const handleChange = e => { let { options } = e.target; options = Array.apply(null, options) const selectedValues = options.filter(x => x.selected).map(x => x.value); setSelectedList(selectedValues); } |
4. Output
Let’s combine all the code together and see how it looks.
App.js
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 | import React, { useState } from 'react'; function App() { const [selectedList, setSelectedList] = useState([]); const handleChange = e => { let { options } = e.target; options = Array.apply(null, options) const selectedValues = options.filter(x => x.selected).map(x => x.value); setSelectedList(selectedValues); } return ( <div className="App"> <h3>React multiselect listbox component - <a href="https://cluemediator.com" target="_blank" rel="noopener noreferrer">Clue Mediator</a></h3> <select multiple name="list-box" onChange={handleChange}> <option value="Value 1">Option 1</option> <option value="Value 2">Option 2</option> <option value="Value 3">Option 3</option> <option value="Value 4">Option 4</option> <option value="Value 5">Option 5</option> <option value="Value 6">Option 6</option> <option value="Value 7">Option 7</option> <option value="Value 8">Option 8</option> </select> <br /><br /> <b>Output:</b> <pre>{JSON.stringify(selectedList)}</pre> </div> ); } export default App; |
Run the application and see the output in the browser.
That’s it for today.
Thank you for reading. Happy Coding..!!