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.
<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.
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
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 class="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.
Output - React multi select listbox component - Clue Mediator
Thatās it for today.
Thank you for reading. Happy Coding..!!