Skip to content

Commit

Permalink
feature: handle outside click
Browse files Browse the repository at this point in the history
  • Loading branch information
kKaskak committed Jul 25, 2024
1 parent d851e85 commit 6fbb583
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/common/MultiselectMenu/MultiselectMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import Dropdown from './Dropdown';
import classNames from 'classnames';
import Icon from '@stremio/stremio-icons/react';
import styles from './MultiselectMenu.less';
import useOutsideClick from 'stremio/common/useOutsideClick';

type Props = {
className?: string,
Expand All @@ -18,7 +19,7 @@ type Props = {

const MultiselectMenu = ({ className, title, options, selectedOption, onSelect }: Props) => {
const [menuOpen, , closeMenu, toggleMenu] = useBinaryState(false);
const multiselectMenuRef = React.useRef<HTMLDivElement>(null);
const multiselectMenuRef = useOutsideClick(() => closeMenu());
const [level, setLevel] = React.useState<number>(0);

const onOptionSelect = (event: any) => {
Expand Down
25 changes: 25 additions & 0 deletions src/common/useOutsideClick.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { useEffect, useRef } from 'react';

const useOutsideClick = (callback: () => void) => {
const ref = useRef<HTMLDivElement>(null);

useEffect(() => {
const handleClickOutside = (event: MouseEvent | TouchEvent) => {
if (ref.current && !ref.current.contains(event.target as Node)) {
callback();
}
};

document.addEventListener('mouseup', handleClickOutside);
document.addEventListener('touchend', handleClickOutside);

return () => {
document.removeEventListener('mouseup', handleClickOutside);
document.removeEventListener('touchend', handleClickOutside);
};
}, [callback]);

return ref;
};

export default useOutsideClick;

0 comments on commit 6fbb583

Please sign in to comment.