Is it possible to control the view property on MUI DatePicker?

115 views Asked by At

I am trying to have different flows for displaying the views based on the user action.

When the user clicks the switch view button I want the flow to be day -> month -> year. The DatePicker opens on day, when I click the switch button the month view will be displayed, and when I click again the switch button the year view will be displayed.

When I select a month from the calendar, I want the flow to be month -> day. When I select a year, I want the flow to be year -> month -> day.

I tried controlling the view property on MUI DatePicker, but it doesn't seem to behave like I expected. It still follows the flow imposed by views. Did I misunderstood how it should work?

export default function DatePickerViews() {
  const [view, setView] = useState<"day" | "year" | "month">("day");

  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      <DatePicker
        views={["day", "month", "year"]}
        view={view}
        slotProps={{
          switchViewButton: {
            onClick: (event) => {
              switch (view) {
                case "day":
                  setView("month");
                  break;
                case "month":
                  setView("year");
                  break;
                case "year":
                  setView("month");
                  break;
              }
            },
          },
        }}
        onMonthChange={(event) => {
          setView("day");
        }}
        onYearChange={(event) => {
          setView("month");
        }}
      />
    </LocalizationProvider>
  );
}
0

There are 0 answers