2020-08-06 08:03:07 +02:00
|
|
|
import React, { useState, useRef } from 'react';
|
2020-08-02 06:20:52 +02:00
|
|
|
import classNames from 'classnames';
|
2020-08-06 08:03:07 +02:00
|
|
|
import Menu from './Menu';
|
|
|
|
import useDocumentClick from 'hooks/useDocumentClick';
|
|
|
|
import Chevron from 'assets/chevron-down.svg';
|
2020-07-31 05:11:43 +02:00
|
|
|
import styles from './Dropdown.module.css';
|
2020-08-06 08:03:07 +02:00
|
|
|
import Icon from './Icon';
|
2020-07-31 05:11:43 +02:00
|
|
|
|
2020-08-06 08:03:07 +02:00
|
|
|
export default function DropDown({
|
|
|
|
value,
|
|
|
|
className,
|
|
|
|
menuClassName,
|
|
|
|
options = [],
|
|
|
|
onChange = () => {},
|
|
|
|
}) {
|
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);
|
|
|
|
}
|
|
|
|
|
2020-08-06 08:03:07 +02:00
|
|
|
useDocumentClick(e => {
|
|
|
|
if (!ref.current.contains(e.target)) {
|
|
|
|
setShowMenu(false);
|
2020-07-31 05:11:43 +02:00
|
|
|
}
|
2020-08-06 08:03:07 +02:00
|
|
|
});
|
2020-07-31 05:11:43 +02:00
|
|
|
|
|
|
|
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}>
|
2020-08-06 08:03:07 +02:00
|
|
|
{options.find(e => e.value === value)?.label}
|
|
|
|
<Icon icon={<Chevron />} size="S" className={styles.icon} />
|
2020-07-31 05:11:43 +02:00
|
|
|
</div>
|
2020-08-06 08:03:07 +02:00
|
|
|
{showMenu && <Menu className={menuClassName} options={options} onSelect={handleSelect} />}
|
2020-07-31 05:11:43 +02:00
|
|
|
</div>
|
|
|
|
);
|
|
|
|
}
|