I am using KeyBoardDatePicker
from material-ui-pickers
with moment utils
for a DatePicker.
import React, { Fragment, useState } from "react";
import {
MuiPickersUtilsProvider,
KeyboardDatePicker
} from "@material-ui/pickers";
import MomentUtils from "@date-io/moment";
import moment from "moment";
function KeyboardDatePickerExample(props) {
const [selectedDate, handleDateChange] = useState(new Date());
return (
<Fragment>
<MuiPickersUtilsProvider libInstance={moment} utils={MomentUtils}>
<KeyboardDatePicker
autoOk={true}
showTodayButton={true}
value={selectedDate}
format="D MMM, YYYY"
onChange={handleDateChange}
minDate={moment().subtract(6, "months")}
maxDate={moment()}
/>
</MuiPickersUtilsProvider>
</Fragment>
);
}
export default KeyboardDatePickerExample;
But it's not working properly.
First, it's not showing the date format properly
and when I try to edit, it it's showing random text and an error invalid date format
.
Here is a sandbox that reproduces the issue.
What am I doing wrong?
EDIT:
After seeing the answer by Nico, I changed the version of date-io/moment
to 1.3.13
Now, the date format is displayed properly
But the edit propblem still exists. What can I do to fix it?
There is no required attribute/prop on the material-ui/date-picker. What can be done is to set a default date say today. And handle the error/required criteria onChange . Save this answer.
This is the fix provided by a colleague of mine. He used inputValue
and value
props of KeyboardDatePicker
. value
takes date object and inputValue
takes formatted date string. And also used rifmFormatter
prop as follows to fix the edit issue. I have also updated the sandbox
import React, { Fragment, useState } from "react";
import {
MuiPickersUtilsProvider,
KeyboardDatePicker
} from "@material-ui/pickers";
import MomentUtils from "@date-io/moment";
import moment from "moment";
function KeyboardDatePickerExample(props) {
const [selectedDate, setDate] = useState(moment());
const [inputValue, setInputValue] = useState(moment().format("YYYY-MM-DD"));
const onDateChange = (date, value) => {
setDate(date);
setInputValue(value);
};
const dateFormatter = str => {
return str;
};
return (
<Fragment>
<MuiPickersUtilsProvider libInstance={moment} utils={MomentUtils}>
<KeyboardDatePicker
autoOk={true}
showTodayButton={true}
value={selectedDate}
format="YYYY-MM-DD"
inputValue={inputValue}
onChange={onDateChange}
rifmFormatter={dateFormatter}
/>
</MuiPickersUtilsProvider>
</Fragment>
);
}
export default KeyboardDatePickerExample;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With