ealush / emoji-picker-react

The most popular React Emoji Picker
https://ealush.com/emoji-picker-react/
MIT License
1.06k stars 172 forks source link

How to auto close picker if clicked outside of it. #232

Open homocodian opened 2 years ago

homocodian commented 2 years ago

Why don't you add ref prop. It would easy if it has ref prop.

homocodian commented 2 years ago

Is there any way to detect outside click on picker.

Tavata-Omar commented 2 years ago

Is there any way to detect outside click on picker.

Add a click event listener to your document then wrap the picker inside a div and use a queryselector to store it in a variable: const emojiWrapper = document.querySelector('.emoji-picker-wrapper')

after that check if your the emoji wrapper contians contains the event you get from the event listener: const emojiWrapperClick = !!emojiWrapper?.contains(e.target) // if undefined coerce to true

elisechant commented 2 years ago

Modify the Picker:

import Picker, { IEmojiPickerProps, IEmojiData } from 'emoji-picker-react';
import { forwardRef } from 'react';

export type EmojiPickerElement = HTMLDivElement;

export const EmojiPicker = forwardRef<EmojiPickerElement, IEmojiPickerProps>(
  (props, ref) => {
    return (
      <div ref={ref}>
        <Picker {...props} />
      </div>
    );
  }
);

EmojiPicker.displayName = 'EmojiPicker';

Then use can use ref like you want to with a useOutsideClick hook 👍

<EmojiPicker ref={refPicker} />
Tpvan5521 commented 1 year ago

I use this:

useEffect(() => {
    function handleClickOutside(event: any) {
      if (
        emojiRef.current &&
        !emojiRef.current.contains(event.target)
      ) {
        setVisibleEmoji(false);
      }
    }
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [emojiRef]);
prashantsihag03 commented 1 year ago

You could also use the ClickAwayListener component from Material UI, I find it to be very easy to use.

showEmojis ? (
  <ClickAwayListener onClickAway={() => {setShowEmojis(false)}}>
    <Box>
      <EmojiPicker />
    </Box>
  </ClickAwayListener>
) : null