import { useRef, useState, useEffect } from "react"; import "./SelectBox.css"; function Option({ option, ...props }) { 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); // return function to be called when unmounted return () => { document.removeEventListener("mousedown", handleClick); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const onOptionClick = (e, option, i) => { e.stopPropagation(); setSelectedItem(i); closeDropdown(); }; const handleSelectedKeyPress = (event) => { if (event.code === "Enter" || event.code === "Space") { setActive((a) => !a); } }; const handleOptionKeyPress = (option, i) => (event) => { if (event.code === "Enter" || event.code === "Space") { onOptionClick(event, option, i); } }; return (
setActive((a) => !a)} >
{options ?
{options.map((opt, i) => (
); }