sudo-archive/src/components/SelectBox.js

71 lines
1.9 KiB
JavaScript
Raw Normal View History

2021-10-25 21:41:42 +00: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>
)
}
export function SelectBox({ options, selectedItem, setSelectedItem }) {
2021-10-25 21:41:42 +00:00
if (!Array.isArray(options)) {
throw new Error("Items must be an array!")
2021-10-25 21:41:42 +00: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);
// return function to be called when unmounted
return () => {
document.removeEventListener("mousedown", handleClick);
};
2021-10-26 12:29:04 +00:00
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
2021-10-25 21:41:42 +00:00
const onOptionClick = (e, option, i) => {
e.stopPropagation()
2021-10-25 21:41:42 +00:00
setSelectedItem(i)
closeDropdown()
}
return (
<div className="select-box" ref={containerRef} onClick={() => setActive(a => !a)}>
2021-10-25 21:41:42 +00:00
<div className={"options-container" + (active ? " active" : "")}>
{options.map((opt, i) => (
<Option option={opt} key={i} onClick={(e) => onOptionClick(e, opt, i)} />
2021-10-25 21:41:42 +00:00
))}
</div>
<div className="selected">
2021-10-25 21:41:42 +00:00
{options ? (
<Option option={options[selectedItem]} />
) : null}
</div>
</div>
)
2021-10-26 12:25:34 +00:00
}