Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Js - clear Material UI Datepicker

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?

like image 995
Luca Mormile Avatar asked Mar 18 '16 12:03

Luca Mormile


2 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;
like image 163
kishore Avatar answered Nov 12 '22 05:11

kishore


You can set the value property as null and it will clear it.

like image 13
Alexg2195 Avatar answered Nov 12 '22 03:11

Alexg2195