Here a multi select with checkbox at the side of the options:
import React, { useState, useRef } from 'react';
import { Form } from 'react-bootstrap';
const MultiSelectDropdown = () => {
const [selectedOptions, setSelectedOptions] = useState([]);
const [isOpen, setIsOpen] = useState(false);
const dropdownRef = useRef(null);
useEffect(() => {
const handleClickOutside = (event) => {
if (dropdownRef.current &&
!dropdownRef.current.contains(event.target)) {
setIsOpen(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, []);
const options = [
{ id: 1, label: 'Option 1' },
{ id: 2, label: 'Option 2' },
{ id: 3, label: 'Option 3' },
{ id: 4, label: 'Option 4' },
{ id: 5, label: 'Option 5' }
];
const toggleDropdown = () => {
setIsOpen(!isOpen);
};
const handleOptionChange = (event) => {
const optionId = parseInt(event.target.value);
const isChecked = event.target.checked;
if (isChecked) {
setSelectedOptions([...selectedOptions, optionId]);
} else {
setSelectedOptions(selectedOptions.filter((id) => id !== optionId));
}
};
return (
<div ref={dropdownRef} className={`dropdown ${isOpen ? 'show' : ''}`}>
<button
style={{width:"20%"}}
className="btn btn-secondary dropdown-toggle"
type="button"
id="multiSelectDropdown"
onClick={toggleDropdown}
>
Select Options
</button>
<div style={{width:"20%"}} className={`dropdown-menu ${isOpen ? 'show' : ''}`} aria-labelledby="multiSelectDropdown">
{options.map((option) => (
<Form.Check
style={{marginLeft:"10%"}}
key={option.id}
type="checkbox"
id={`option_${option.id}`}
label={option.label}
checked={selectedOptions.includes(option.id)}
onChange={handleOptionChange}
value={option.id}
/>
))}
</div>
{JSON.stringify(selectedOptions)}
</div>
);
};
export default MultiSelectDropdown;