1

In react-datepicker with custom header, you get access to methods called increaseMonth() and decreaseMonth() (same for year). These methods change the view without changing the date. What I need is to mimic these in my Datepicker component.

My goal is to change the view when clicking the outside-month dates without changing the selected date.

Does datepicker have a value you can set that's different from selected? Like focused or currentDate something along those lines. Either manually changing that value, or manually invoking increase/decrease Month methods should work, but I couldn't find anything on how to do this.

What I've tried:

If I .focus() the selected date, the calendar will switch to the month that was clicked, but I have no way of differentiating between an in-month date, and outside-month date this way. I can compare if the clicked month is different than the current month, but that doesn't work when you try to go back to the current month. This also has a problem on the first load when the selected date is still null.

Focusing target

  // onChangeHandler
  if (selectedDate?.getMonth() !== clickedDate?.getMonth()) {
    selfRef.current.focus();
    return; // so the datepicker doesn't close
  } 
        
  // else user clicked in-month date... 
  // setSelectedDate and close datepicker

Another workaround, but this changes the date when navigating through the header which is not ideal

  onMonthChange={setSelectedDate}
symphony
  • 21
  • 4

1 Answers1

1

I was overthinking this. I solved it by creating my own current date variable rather than try to get date-picker to handle it.

// DatePicker component
  // ...
  const dateInView = useRef<Date>(selectedDate ?? new Date());

  // onChangeHandler
    if (viewType === "date") {
      if (dateInView.current.getMonth() !== date.getMonth()) {
        dateInView.current = date;
        return;
      }

      dateInView.current = date;
    // set selected date and close datepicker
    // ...
    
  return <DatePicker
           shouldCloseOnSelect={false}
           onMonthChange={(date) => { dateInView.current = date; }}
           ...props
         />
symphony
  • 21
  • 4