S
S
Sergey2021-09-02 13:35:26
React
Sergey, 2021-09-02 13:35:26

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>
  );
};


What is the best way to do this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
ParaBellum577, 2021-09-02
@justedoit

Here is a similar solution
Or something like this

handleClickOutside(event) {
        if (myRef && !myRef.current.contains(event.target)) {
            alert('You clicked outside of me!');
        }
    }

I
Ignat Lomkov, 2021-09-02
@cleverocheck

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 question

Ask a Question

731 491 924 answers to any question