Open homocodian opened 2 years ago
Is there any way to detect outside click on picker.
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
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} />
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]);
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
Why don't you add ref prop. It would easy if it has ref prop.