Bhavesh Damor
Bhavesh Damor

Reputation: 81

How to display years inside the calendar UI in descending order for material-ui Date Picker

Sample Code I used -

import "./styles.css";
import { DatePicker } from "@mui/x-date-pickers";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDateFns } from "@mui/x-date-pickers/AdapterDateFns";
import { useState } from "react";
import moment from "moment";

export default function App() {
  const [open, setOpen] = useState(false);
  const [dateValue, setDateValue] = useState("");
  return (
    <div className="App">
      <LocalizationProvider dateAdapter={AdapterDateFns}>
        <DatePicker
          open={open}
          openTo="year"
          onOpen={() => setOpen(true)}
          onClose={() => setOpen(false)}
          value={dateValue}
          onChange={(v) => setDateValue(v)}
          InputAdornmentProps={{ position: "start" }}
          views={["year", "month", "day"]}
          minDate={moment("12/31/1930").toDate()}
          maxDate={moment("1/31/2008").toDate()}
          inputFormat={"MMMM-yyyy"}
        />
      </LocalizationProvider>      
    </div>
  );
}

Dependencies -

"@emotion/react": "11.10.6",
"@emotion/styled": "11.10.6",
"@mui/material": "5.11.14",
"@mui/x-date-pickers": "6.0.3",
"date-fns": "2.29.3",

This is what the calendar looks like -

This is the default calendar view

I want the order of the years in descending order so that the user does not have to scroll at the bottom of the calendar UI to select latest years as per the maxDate provided in props.

I went through the docs for the DatePicker component but didn't find a prop to reverse the year order.

I also tried implementing this - How to show year list in a descending order for DatePicker component in MUI , but since the mui versions differ I was not able to replicate it.

Could you please help me with this issue , it would be of great help.Thank you.

P.S - Here is the above mentioned code

Upvotes: 1

Views: 520

Answers (1)

Jordan Aasen
Jordan Aasen

Reputation: 83

You'll need to extend the getYearRange implementation of the localization provider (in your case AdapterDateFns). Here's an example:

class ExtendedAdapterDateFns extends AdapterDateFns {
  getYearRange = (start: Date, end: Date) => {
    const startDate = startOfYear(start)
    const endDate = endOfYear(end)
    const years = []

    let currentYear = endDate
    while (isBefore(startDate, currentYear)) {
      years.push(currentYear)
      currentYear = addYears(currentYear, -1)
    }
    return years
  }
}
    <LocalizationProvider dateAdapter={ExtendedAdapterDateFns}>

Upvotes: 1

Related Questions