2021-10-25 23:41:42 +02:00
|
|
|
import { useRef, useState, useEffect } from "react"
|
|
|
|
import "./SelectBox.css"
|
|
|
|
|
|
|
|
function Option({ option, onClick }) {
|
|
|
|
return (
|
|
|
|
<div className="option" onClick={onClick}>
|
|
|
|
<input
|
|
|
|
type="radio"
|
|
|
|
className="radio"
|
|
|
|
id={option.id} />
|
|
|
|
<label htmlFor={option.id}>
|
|
|
|
<div className="item">{option.name}</div>
|
|
|
|
</label>
|
|
|
|
</div>
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2021-10-26 14:17:11 +02:00
|
|
|
export function SelectBox({ options, selectedItem, setSelectedItem }) {
|
2021-10-25 23:41:42 +02:00
|
|
|
if (!Array.isArray(options)) {
|
2021-10-26 14:17:11 +02:00
|
|
|
throw new Error("Items must be an array!")
|
2021-10-25 23:41:42 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
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);
|
2021-10-26 14:17:11 +02:00
|
|
|
//document.addEventListener("scroll", closeDropdown);
|
2021-10-25 23:41:42 +02:00
|
|
|
// return function to be called when unmounted
|
|
|
|
return () => {
|
|
|
|
document.removeEventListener("mousedown", handleClick);
|
|
|
|
document.removeEventListener("scroll", closeDropdown)
|
|
|
|
};
|
|
|
|
}, []);
|
|
|
|
|
2021-10-26 14:17:11 +02:00
|
|
|
const onOptionClick = (e, option, i) => {
|
|
|
|
e.stopPropagation()
|
2021-10-25 23:41:42 +02:00
|
|
|
setSelectedItem(i)
|
|
|
|
closeDropdown()
|
|
|
|
}
|
|
|
|
|
|
|
|
return (
|
2021-10-26 14:17:11 +02:00
|
|
|
<div className="select-box" ref={containerRef} onClick={() => setActive(a => !a)}>
|
2021-10-25 23:41:42 +02:00
|
|
|
<div className={"options-container" + (active ? " active" : "")}>
|
|
|
|
{options.map((opt, i) => (
|
2021-10-26 14:17:11 +02:00
|
|
|
<Option option={opt} key={i} onClick={(e) => onOptionClick(e, opt, i)} />
|
2021-10-25 23:41:42 +02:00
|
|
|
))}
|
|
|
|
</div>
|
2021-10-26 14:17:11 +02:00
|
|
|
<div className="selected">
|
2021-10-25 23:41:42 +02:00
|
|
|
{options ? (
|
|
|
|
<Option option={options[selectedItem]} />
|
|
|
|
) : null}
|
|
|
|
</div>
|
|
|
|
</div>
|
|
|
|
)
|
|
|
|
}
|