简体   繁体   中英

Material ui DatePicker enable only year

Is there any way to show only years in Material UI DatePicker with react ? I want to allow the user to be able to select only the year and not months or days . Note: The option openToYearSelection does not achieve this neither does autoOk help.

I came across the same issue and the way i have sorted it out is by using material-ui-pickers library Here is an example:

import React, { Fragment, useState } from "react";
import { DatePicker, InlineDatePicker } from "material-ui-pickers";

function YearMonthPicker(props) {
  const [selectedDate, handleDateChange] = useState(new Date());

  return (
    <Fragment>
      <div className="picker">
        <DatePicker
          views={["year"]}
          label="Year only"
          value={selectedDate}
          onChange={handleDateChange}
          animateYearScrolling
        />
      </div>
    </Fragment>
  );
}

export default YearMonthPicker;

Use views prop for mui DatePicker.

<DatePicker views={['year']} />

Also you can disable some years using shouldDisableYear prop.

https://mui.com/x/api/date-pickers/date-picker/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM