import { useRef, useState, useEffect } from "react"
import "./SelectBox.css"
function Option({ option, onClick }) {
return (
)
}
export function SelectBox({ options, selectedItem, setSelectedItem }) {
if (!Array.isArray(options)) {
throw new Error("Items must be an array!")
}
const [active, setActive] = useState(false)
const containerRef = useRef();
const handleClick = e => {
if (containerRef.current.contains(e.target)) {
// inside click
return;
}
// outside click
closeDropdown()
};
const closeDropdown = () => {
setActive(false)
}
useEffect(() => {
// add when mounted
document.addEventListener("mousedown", handleClick);
//document.addEventListener("scroll", closeDropdown);
// return function to be called when unmounted
return () => {
document.removeEventListener("mousedown", handleClick);
document.removeEventListener("scroll", closeDropdown)
};
}, []);
const onOptionClick = (e, option, i) => {
e.stopPropagation()
setSelectedItem(i)
closeDropdown()
}
return (
setActive(a => !a)}>
{options.map((opt, i) => (
{options ? (
) : null}
)
}