umami/components/common/MenuButton.js

60 lines
1.4 KiB
JavaScript
Raw Normal View History

2020-09-21 06:31:53 +02:00
import React, { useState, useRef } from 'react';
import classNames from 'classnames';
import Menu from 'components/common/Menu';
import Button from 'components/common/Button';
import useDocumentClick from 'hooks/useDocumentClick';
import styles from './MenuButton.module.css';
export default function MenuButton({
icon,
value,
options,
2020-10-02 21:15:42 +02:00
menuClassname,
2020-09-21 06:31:53 +02:00
menuPosition = 'bottom',
menuAlign = 'right',
onSelect,
renderValue,
}) {
const [showMenu, setShowMenu] = useState(false);
const ref = useRef();
const selectedOption = options.find(e => e.value === value);
function handleSelect(value) {
onSelect(value);
setShowMenu(false);
}
function toggleMenu() {
setShowMenu(state => !state);
}
useDocumentClick(e => {
if (!ref.current.contains(e.target)) {
setShowMenu(false);
}
});
return (
<div className={styles.container} ref={ref}>
<Button
icon={icon}
2020-09-22 06:34:55 +02:00
className={classNames(styles.button, { [styles.open]: showMenu })}
2020-09-21 06:31:53 +02:00
onClick={toggleMenu}
variant="light"
>
<div className={styles.text}>{renderValue ? renderValue(selectedOption) : value}</div>
</Button>
{showMenu && (
<Menu
2020-10-03 19:53:06 +02:00
className={menuClassname}
2020-09-21 06:31:53 +02:00
options={options}
selectedOption={selectedOption}
onSelect={handleSelect}
float={menuPosition}
align={menuAlign}
/>
)}
</div>
);
}