import React, { FC, useState, useEffect, useRef } from 'react' import styles from './select.module.css' type SelectTypes = { /** * Action when selecting */ onChange(): void; /** * Dropdown data */ data: {value: string, label: string}[]; /** * Dropdown title */ placeholder: string; /** * Color of component */ color: string; /** * Data value */ value: string; } export const Select: FC = ( { value, onChange, data, placeholder, color } ) => { const rootRef = useRef(null); const optionRef = useRef(null); const [isOpen, setIsOpen] = useState(false); const [curElem, setCurElem] = useState(null); const handleChange = (value) => { onChange && onChange(value); setIsOpen(false); } useEffect(() => { const elem = (data || []).find(e => e.value === value); setCurElem(elem); }, [value, data]) useEffect(() => { const handleClickOutside = (event) => { if (optionRef.current && !optionRef.current.contains(event.target)) { if(!rootRef.current || (rootRef.current && !rootRef.current.contains(event.target))) { setIsOpen(false); } } } document.addEventListener('mousedown', handleClickOutside); return () => { document.removeEventListener('mousedown', handleClickOutside); } }, [optionRef]); return (
setIsOpen(!isOpen)} >
{ curElem ? curElem.label : placeholder || ''}
{ isOpen && data &&
{ data.map(d => (
handleChange(d.value)} className={`px-3 py-3 hover:bg-gray-200 cursor-pointer`} > {d.label}
)) }
}
) };