I would like to add a 'clear' button to a DatePicker from @mui/lab (5.0.0-alpha.55).
What I am attempting:
date field in state, passed as the value prop to DatePickerdate to null when desired to 'clear' the value & inputThe behaviour I observe:
date is valid, it works as expected, and the input is cleareddate is not valid, the error is cleared, but the invalid date still stays in the input.The rudimentary version I have attempted which shows the behaviour above can be seen here.
If you input a partial date, then click clear, you can observe that the input does not get cleared.
I would prefer to avoid a solution that involves changing the key, as that brings other issues, such as not respecting an external source changing the date to null, and needing additional hacks to respect the label transition when clearing the input.
For @mui/x-date-pickers v5 you could do:
<DatePicker
componentsProps={{
actionBar: {
actions: ['clear'],
},
}}
onAccept={(newDate) => {
console.log(newDate);
}}
/>
and see if newDate is null.
Important updates:
@mui/x-date-pickers v6 please see the other commentclear will make the user stuck on mobile. Consider having ['clear', 'accept'] for mobile and ['clear'] for desktop, or simpler, merge the behavior by using the property closeOnSelect={true|false} to force on both platforms.@mui/x-date-pickers package version v6.16.0 now has this feature built in:
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
<DatePicker
slotProps={{ field: { clearable: true } }}
/>
source: https://github.com/mui/mui-x/releases/tag/v6.16.0
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