React Js - clear Material UI Datepicker

Viewed 13765

I'm having some troubles with Material UI's Datepicker, I'm searching a way to reset its field but I didn't find a way to do it. I've also consulted this issue. Can someone help me please?

4 Answers

I found the same issue, researched, and got a solution for that,

We can use InputAdornments to have a close button in that.

Remember, we have to use event.stopPropagation() to stop the DatePicker pop up on click of Close button.

You may have a look at here, https://codesandbox.io/s/material-ui-pickers-usage-demo-forked-tptz3?file=/src/App.jsx or https://tptz3.csb.app/

import React, { useState } from "react";
import DateFnsUtils from "@date-io/date-fns";
import { MuiPickersUtilsProvider, DatePicker } from "@material-ui/pickers";

import ClearIcon from "@material-ui/icons/Clear";
import { IconButton } from "@material-ui/core";

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

  function handleClr(e) {
    e.stopPropagation();
    handleDateChange(null);
  }
  return (
    <MuiPickersUtilsProvider utils={DateFnsUtils}>
      <DatePicker
        autoOk
        variant="inline"
        format="dd/MM/yyyy"
        value={selectedDate}
        onChange={handleDateChange}
        InputProps={{
          endAdornment: (
            <IconButton onClick={(e) => handleClr(e)}>
              <ClearIcon />
            </IconButton>
          )
        }}
      />
    </MuiPickersUtilsProvider>
  );
}

export default App;

In material ui version upper 4.0.0 you have to set empty string to reset the date pickers.

    value={person.birthday ?? ''}
Related