Delta Boukensha
Delta Boukensha

Reputation: 170

How to programmatically open with button @material-ui/core native textfield type date dialog?

How can I use a button to programmatically open the dialog of this @material-ui/core native textfield type date dialog?

I have already looked into import { DatePicker } from "@material-ui/pickers" And deemed it overkill for my application also I had some issues there

import { TextField } from "@material-ui/core"

<TextField type="date" defaultValue="2017-05-24"/> //how to open this programmatically
<Button onClick={() => {}}>Button That Opens The Date Dialog</Button>

I am using

"react": "^17.0.2",
"@material-ui/core": "^4.12.3",

Thanks for any help

Upvotes: 0

Views: 614

Answers (2)

tsmith023
tsmith023

Reputation: 311

I would do this by manipulating state so that the button changes some boolean that then triggers the dialogue to open. So, being clearer, have some value in state, like dateOpened, set to false initially. Have the onClick in the button update this value to be the opposite value, which is true at first. Then have a TextField that displays based on the value of dateOpened.

const [dateOpened, setDateOpened] = useState(false);
return (
  <Button onClick={() => setDateOpened(() => (dateOpened ? false : true))}/>
    {
      dateOpened ? <TextField type="date" defaultValue="2017-05-24"/> : <div>Date not opened!</div>
    }
  }
);

The ? operator is the conditional if you've not met it before. Then, if you click the button again, it will hide the TextField since the onClick will change dateOpened from true back to false.

Upvotes: 1

Delta Boukensha
Delta Boukensha

Reputation: 170

After some more digging around it seems it is not possible to trigger the native input type date dialog

How to trigger mouse click event on react component to open date picker

However it is possible to trigger the dialog from import { DatePicker } from "@material-ui/pickers"

Combined solution based on t.smith answer Thanks

{!record.trash && (
  <Tooltip arrow title="Calendar">
    <Button
      disabled={record.trash}
      onClick={() => {
        setShow({
          ...show,
          ["datepicker_" + record.id]: true,
        })
      }}
    >
      <CalendarTodayIcon />
    </Button>
  </Tooltip>
)}
{show["datepicker_" + record.id] && (
  <DatePicker
    value={record.date}
    hidden={true}
    open={true}
    onChange={async (d) => {
      await updateRecord({
        ...record,
        date: d.toISOString(),
      })
    }}
    onClose={() => {
      setShow({
        ...show,
        ["datepicker_" + record.id]: false,
      })
    }}
  ></DatePicker>
)}

Upvotes: 1

Related Questions