import React, { useEffect, useRef, useState } from "react"; import { theme } from "../../theme"; import { Icon } from "../Icon"; export interface DropdownProps { onChange: (value: string) => void; options: Array<{ label: string; value: string }>; selected?: string; open?: boolean; } const DropdownOptions: React.FC = (props) => { return (
{props.options.map(({ label, value }) => (
{ props.onChange(value); }} >
{props.selected === value ? : ""}
{label}
))}
); }; /** * Temp comp until @nocodelytics/components is ready * We'll use which will also include types */ export const Dropdown: React.FC = (props) => { if (!props.options.length) { throw new Error(`Dropdown requires options`); } const [isOpen, setIsOpen] = useState(props.open || false); const [selected, setSelected] = useState( props.selected || props.options[0].value ); const ref = useRef(null); useEffect(() => { function handleClickOutside(event: Event) { if (ref.current && !ref.current.contains(event.target as Node)) { setIsOpen(false); } } document.addEventListener("mousedown", handleClickOutside); return () => { document.removeEventListener("mousedown", handleClickOutside); }; }, [ref]); return (
setIsOpen(!isOpen)} style={{ position: "relative", ...theme.text.primary, ...theme.background.secondary, ...theme.border.primary, cursor: "pointer", maxWidth: 150, }} >
{props.options.find(({ value }) => selected === value)!.label}
{isOpen && ( { setIsOpen(false); setSelected(value); props.onChange(value); }} /> )}
); };