Here’s a simple React example for a dynamic multi-select dropdown where you can select/deselect options and show selected options as tags.
Code Example
import React, { useState } from "react";
import "./MultiSelect.css"; // optional for styling
const options = ["Apple", "Banana", "Orange", "Mango", "Grapes"];
function MultiSelectDropdown() {
const [selected, setSelected] = useState([]);
// Toggle selection
const handleSelect = (option) => {
if (selected.includes(option)) {
setSelected(selected.filter((item) => item !== option)); // deselect
} else {
setSelected([...selected, option]); // select
}
};
// Remove tag
const removeTag = (option) => {
setSelected(selected.filter((item) => item !== option));
};
return (
<div className="multi-select-container">
<div className="selected-tags">
{selected.map((item) => (
<span key={item} className="tag">
{item} <button onClick={() => removeTag(item)}>x</button>
</span>
))}
</div>
<div className="dropdown">
{options.map((option) => (
<div
key={option}
className={`dropdown-item ${
selected.includes(option) ? "selected" : ""
}`}
onClick={() => handleSelect(option)}
>
{option}
</div>
))}
</div>
</div>
);
}
export default MultiSelectDropdown;
CSS Example (MultiSelect.css)
.multi-select-container {
width: 250px;
border: 1px solid #ccc;
padding: 5px;
border-radius: 5px;
font-family: Arial, sans-serif;
}
.selected-tags {
display: flex;
flex-wrap: wrap;
gap: 5px;
margin-bottom: 5px;
}
.tag {
background: #007bff;
color: white;
padding: 2px 5px;
border-radius: 3px;
display: flex;
align-items: center;
gap: 5px;
}
.tag button {
background: transparent;
border: none;
color: white;
cursor: pointer;
}
.dropdown {
border-top: 1px solid #ccc;
}
.dropdown-item {
padding: 5px;
cursor: pointer;
}
.dropdown-item.selected {
background: #e0f0ff;
}
How it works:
- State
selectedholds currently selected items. - Clicking an option toggles selection (
handleSelect). - Selected options are displayed as tags with a remove button.
- Deselecting can be done either by clicking the tag button or selecting the option again.
⚡ In short:
Use React state to track selected items, map over options to render the dropdown, and display selected items as removable tags for a dynamic multi-select dropdown.