Reputation: 339
I am having an issue utilizing the DayPicker
api for use of the pop-up calendar. I need to close/hide when I click outside the calendar. I want to work like the DayPickerInput
component work but with our the textbox input. I ONLY need the popup calendar. Using onBlur
only partially works because if I click a week, it does not immediately recognize the focus the calendar container. I am really struggling with this and I am sure there is a simple solution.
Here is code snippet:
<div className={calendarPopOut} onBlur={handleClickOutside}>
<DayPicker
disabledDays={currentCalendarWeek}
className={dayPicker}
showOutsideDays
month={currentSelectedMonth}
toMonth={currentMonth}
weekdayElement={<ThreeCharacterAbv />}
onDayClick={handleChange}
onBlur={handleClickOutside}
/>
</div>
Upvotes: 3
Views: 1366
Reputation: 1803
You can create a ref to the datepicker container and create a event listener on document click and close the datepicker.
const datePickerRef = useRef<HTMLDivElement | null>(null);
// Add event listener to close the date picker when clicked outside
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
// Close the date picker only when clicked outside
if (
datePickerRef.current &&
event.target instanceof Node &&
!datePickerRef.current.contains(event.target)
) {
handleCloseDayPicker();
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, [handleCloseDayPicker]);
<div className={calendarPopOut} ref={datePickerRef}>
<DayPicker
disabledDays={currentCalendarWeek}
className={dayPicker}
showOutsideDays
month={currentSelectedMonth}
toMonth={currentMonth}
weekdayElement={<ThreeCharacterAbv />}
onDayClick={handleChange}
onBlur={handleCloseDayPicker}
/>
</div>
I have specified the types you can remove them if your not using typescript. Hope this helps!
Upvotes: 0