React-calendar Ui not switching when value is set from function after single interaction

428 Views Asked by At

The UI of the react calendar is not switching to the respective month when the value is set functionally after the calendar has been touched (dirty).

export default function App() {
  const [date, setDate] = useState([
    new Date('2022-05-10'),
    new Date('2022-05-15'),
  ]);
  return (
    <>
      <p>
        <div>
          <button onClick={() => setDate([new Date('2022-11-02'), new Date('2022-11-08')])}>click</button>
          <Calendar
            value={date}
            onChange={(v) => {
              setDate(v);
            }}
            selectRange
            minDate={new Date()}
            defaultStartDate={date[0]}
          />
        </div>
      </p>
)
}

If the button is clicked post a manual selection of dates has been made. (calendar component clicked and selection made). Then the date value changes but the UI stays intact.

1

There are 1 best solutions below

0
On

You have to set the activeStartDate prop manually also to have a fully controlled calendar.

This is the code that worked for me (I receive the controlled date from props):

export default function Calendar({ date, handleDateChange }) {
  return <MiniCalendar
           value={date.toDate()}
           activeStartDate={date.startOf('month').toDate()}
           onChange={handleDateChange}
           showNavigation={false} />
}

I use dayjs dates to handle my state and retrieve the first day of the month.

Useful link: https://github.com/wojtekmaj/react-calendar/issues/358.