2020-07-31 05:11:43 +02:00
|
|
|
import React, { useState, useEffect, useRef } from 'react';
|
2020-08-02 06:20:52 +02:00
|
|
|
import classNames from 'classnames';
|
2020-07-31 05:11:43 +02:00
|
|
|
import styles from './Dropdown.module.css';
|
|
|
|
|
2020-08-02 06:20:52 +02:00
|
|
|
export default function DropDown({ value, options = [], onChange, className }) {
|
2020-07-31 05:11:43 +02:00
|
|
|
const [showMenu, setShowMenu] = useState(false);
|
|
|
|
const ref = useRef();
|
|
|
|
|
|
|
|
function handleShowMenu() {
|
|
|
|
setShowMenu(state => !state);
|
|
|
|
}
|
|
|
|
|
2020-07-31 07:40:16 +02:00
|
|
|
function handleSelect(value, e) {
|
|
|
|
e.stopPropagation();
|
|
|
|
setShowMenu(false);
|
2020-07-31 05:11:43 +02:00
|
|
|
onChange(value);
|
|
|
|
}
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
function hideMenu(e) {
|
2020-07-31 07:40:16 +02:00
|
|
|
if (!ref.current.contains(e.target)) {
|
2020-07-31 05:11:43 +02:00
|
|
|
setShowMenu(false);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
document.body.addEventListener('click', hideMenu);
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
document.body.removeEventListener('click', hideMenu);
|
|
|
|
};
|
|
|
|
}, [ref]);
|
|
|
|
|
|
|
|
return (
|
2020-08-02 06:20:52 +02:00
|
|
|
<div ref={ref} className={classNames(styles.dropdown, className)} onClick={handleShowMenu}>
|
2020-07-31 05:11:43 +02:00
|
|
|
<div className={styles.value}>
|
|
|
|
{options.find(e => e.value === value).label}
|
|
|
|
<div className={styles.caret} />
|
|
|
|
</div>
|
|
|
|
{showMenu && (
|
|
|
|
<div className={styles.menu}>
|
|
|
|
{options.map(({ label, value }) => (
|
|
|
|
<div key={value} className={styles.option} onClick={e => handleSelect(value, e)}>
|
|
|
|
{label}
|
|
|
|
</div>
|
|
|
|
))}
|
|
|
|
</div>
|
|
|
|
)}
|
|
|
|
</div>
|
|
|
|
);
|
|
|
|
}
|