2022-12-29 00:43:22 +01:00
|
|
|
import { useState, useRef } from 'react';
|
2021-02-16 12:57:18 +01:00
|
|
|
import PropTypes from 'prop-types';
|
2020-08-02 06:20:52 +02:00
|
|
|
import classNames from 'classnames';
|
2020-08-08 05:36:57 +02:00
|
|
|
import Menu from './Menu';
|
2020-08-06 08:03:07 +02:00
|
|
|
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';
|
2022-12-27 01:57:59 +01:00
|
|
|
import { Icon } from 'react-basics';
|
2020-07-31 05:11:43 +02:00
|
|
|
|
2021-02-16 12:57:18 +01:00
|
|
|
function DropDown({ value, className, menuClassName, options = [], onChange = () => {} }) {
|
2020-07-31 05:11:43 +02:00
|
|
|
const [showMenu, setShowMenu] = useState(false);
|
|
|
|
const ref = useRef();
|
2020-09-21 06:31:53 +02:00
|
|
|
const selectedOption = options.find(e => e.value === value);
|
2020-07-31 05:11:43 +02:00
|
|
|
|
|
|
|
function handleShowMenu() {
|
|
|
|
setShowMenu(state => !state);
|
|
|
|
}
|
|
|
|
|
2020-08-31 23:11:30 +02:00
|
|
|
function handleSelect(selected, e) {
|
2020-07-31 07:40:16 +02:00
|
|
|
e.stopPropagation();
|
|
|
|
setShowMenu(false);
|
2020-09-13 10:26:54 +02:00
|
|
|
|
|
|
|
onChange(selected);
|
2020-07-31 05:11:43 +02:00
|
|
|
}
|
|
|
|
|
2020-08-06 08:03:07 +02:00
|
|
|
useDocumentClick(e => {
|
2021-01-21 04:11:36 +01:00
|
|
|
if (!ref.current?.contains(e.target)) {
|
2020-08-06 08:03:07 +02:00
|
|
|
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-09-27 09:51:29 +02:00
|
|
|
<div className={styles.text}>{options.find(e => e.value === value)?.label || value}</div>
|
2022-12-27 01:57:59 +01:00
|
|
|
<Icon className={styles.icon} size="small">
|
|
|
|
<Chevron />
|
|
|
|
</Icon>
|
2020-07-31 05:11:43 +02:00
|
|
|
</div>
|
2020-08-10 00:13:38 +02:00
|
|
|
{showMenu && (
|
2020-09-21 06:31:53 +02:00
|
|
|
<Menu
|
|
|
|
className={menuClassName}
|
|
|
|
options={options}
|
|
|
|
selectedOption={selectedOption}
|
|
|
|
onSelect={handleSelect}
|
|
|
|
float="bottom"
|
|
|
|
/>
|
2020-08-10 00:13:38 +02:00
|
|
|
)}
|
2020-07-31 05:11:43 +02:00
|
|
|
</div>
|
|
|
|
);
|
|
|
|
}
|
2021-02-16 12:57:18 +01:00
|
|
|
|
|
|
|
DropDown.propTypes = {
|
|
|
|
value: PropTypes.any,
|
|
|
|
className: PropTypes.string,
|
|
|
|
menuClassName: PropTypes.string,
|
|
|
|
options: PropTypes.arrayOf(
|
|
|
|
PropTypes.shape({
|
|
|
|
value: PropTypes.any.isRequired,
|
|
|
|
label: PropTypes.node,
|
|
|
|
}),
|
|
|
|
),
|
|
|
|
onChange: PropTypes.func,
|
|
|
|
};
|
|
|
|
|
|
|
|
export default DropDown;
|