Answer the question
In order to leave comments, you need to log in
How to close the list on click outside the block?
Good day!
There is a Dropdown component.
It is necessary to close the open list by clicking outside the block.
const Dropdown: FC<DropdownType> = ({
options,
onClick,
title,
}): JSX.Element => {
const [isOpen, setOpen] = useState<boolean>(false);
const [activeOption, setActiveOption] = useState<DropdownOptionType>(
options.find((opt) => opt.default) || options[0],
);
const toggling = useCallback(() => setOpen(!isOpen), [isOpen]);
useEffect(() => {
const { slug } = activeOption;
onClick(slug);
}, [onClick, activeOption]);
const onOptionClicked = useCallback(
(option: DropdownOptionType) => {
setActiveOption(option);
toggling();
},
[toggling],
);
return (
<div className={cn('dropdown')}>
{title && <p className={cn('title')}>{title}</p>}
<DropdownToggle
isOpen={isOpen}
onClick={toggling}
option={activeOption}
/>
{isOpen && (
<DropdownList
activeOption={activeOption}
onOptionClicked={onOptionClicked}
options={options}
/>
)}
</div>
);
};
Answer the question
In order to leave comments, you need to log in
Here is a similar solution
Or something like this
handleClickOutside(event) {
if (myRef && !myRef.current.contains(event.target)) {
alert('You clicked outside of me!');
}
}
Do not write a bicycle, everything has already been invented for you. Here is a nice tracking tool from Material UI
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question