1
0
Fork 0
mirror of https://github.com/sussy-code/smov.git synced 2024-12-22 14:57:40 +01:00
smov/src/components/SelectBox.js

71 lines
2 KiB
JavaScript
Raw Normal View History

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>
)
}
export function SelectBox({ options, selectedItem, setSelectedItem }) {
2021-10-25 23:41:42 +02:00
if (!Array.isArray(options)) {
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);
//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)
};
}, []);
const onOptionClick = (e, option, i) => {
e.stopPropagation()
2021-10-25 23:41:42 +02:00
setSelectedItem(i)
closeDropdown()
}
return (
<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) => (
<Option option={opt} key={i} onClick={(e) => onOptionClick(e, opt, i)} />
2021-10-25 23:41:42 +02:00
))}
</div>
<div className="selected">
2021-10-25 23:41:42 +02:00
{options ? (
<Option option={options[selectedItem]} />
) : null}
</div>
</div>
)
}