Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
26
rated 0 times [  27] [ 1]  / answers: 1 / hits: 10542  / 4 Years ago, sun, september 13, 2020, 12:00:00

As soon as you start typing inside the DatePicker component, the validation is triggered.


How does one trigger validation on blur instead of onInputChange when using


@material-ui/pickers meant for material-ui v4


Passing the value to the blur function should work and omitting on change, but as soon as you remove the onChange event the code breaks.


Example


export default function MaterialUIPickers() {
const [selectedDate, setSelectedDate] = React.useState();

const handleDateChange = (date) => {
setSelectedDate(date);
};

const handleBlur = (e) => {
setSelectedDate(e.target.value);
};

return (
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDatePicker
id="date-picker-dialog"
format="MM/dd/yyyy"
value={selectedDate}
onChange={handleDateChange}
onBlur={handleBlur}
/>
</MuiPickersUtilsProvider>
);
}

Muiv4 documentation


Stackblitz example


More From » reactjs

 Answers
12

Since onChange is mandatory returning undefined in the callback solves the issue but breaks the datePicker select option (does not apply the selected date to the input field).


Because of the above, onAccept should be used thereby internal state logic can be omitted which is crucial.


Code


export default function MaterialUIPickers() {
const [selectedDate, setSelectedDate] = React.useState();

const handleBlur = (e) => {
setSelectedDate(e.target.value);
};

return (
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<KeyboardDatePicker
id="date-picker-dialog"
format="MM/dd/yyyy"
value={selectedDate}
onChange={()=>undefined}
onAccept{setSelectedDate}
onBlur={handleBlur}
/>
</MuiPickersUtilsProvider>
);
}

Stackblitz


[#2691] Wednesday, September 9, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leog

Total Points: 225
Total Questions: 113
Total Answers: 118

Location: Oman
Member since Wed, Apr 12, 2023
1 Year ago
leog questions
;