Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I clear MUI X Date Picker input?

I would like to add a 'clear' button to a DatePicker from @mui/lab (5.0.0-alpha.55).

What I am attempting:

  • Store a date field in state, passed as the value prop to DatePicker
  • Change the date to null when desired to 'clear' the value & input

The behaviour I observe:

  • If the date is valid, it works as expected, and the input is cleared
  • If the date 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.

like image 825
Josh Fraser Avatar asked Sep 10 '25 08:09

Josh Fraser


2 Answers

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:

  1. For @mui/x-date-pickers v6 please see the other comment
  2. By default mobile and desktop don't have the same behavior, and just specifying clear 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.
like image 112
Thomas Ramé Avatar answered Sep 13 '25 04:09

Thomas Ramé


@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

like image 35
Titenis Avatar answered Sep 13 '25 04:09

Titenis