Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React material UI open datepicker on button click

I am using react material ui for Datepicker .

 <TextField
        id="datetime-local"
        label="Next appointment"
        type="datetime-local"
        defaultValue="2017-05-24T10:30"
        sx={{ width: 250 }}
        InputLabelProps={{
          shrink: true,
        }}
      />

i want to open this date picker on click of a button.

Thanks in advance.

like image 288
sourabh Avatar asked Jul 22 '26 04:07

sourabh


1 Answers

You can achieve this by using the showPicker function on the HTMLInputElement.

Create a ref for the native input element. You can pass the ref down to the input using inputProps.

const inputRef = useRef(null);

const handleClick = () => {
  // check if the ref is set
  if (inputRef.current === null) return;
  inputRef.current.showPicker();
};

return (
  <>
    <TextField
      id="datetime-local"
      label="Next appointment"
      type="datetime-local"
      defaultValue="2017-05-24T10:30"
      sx={{ width: 250 }}
      inputProps={{
        ref: inputRef,
      }}
      InputLabelProps={{
        shrink: true,
      }}
    />
    <button onClick={handleClick}>open datepicker</button>
  </>
);
like image 111
RubenSmn Avatar answered Jul 24 '26 16:07

RubenSmn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!