react-datetime: How to set the time to now() from a button

1.3k views Asked by At

I am using react-datetime

enter image description here

I want the user to easily set the time to current time using a button Immediate. Instead of selecting the current time manually.

I am trying the below


const [currentDateTime, setcurrentDateTime] = useState(null);
<Datetime
    inputProps={{
        placeholder: "MM-DD-YYYY HH:mm",
        required: true,
    }}
    viewMode="time"
    value={currentDateTime} <--- THE PROBLEM WITH THIS IS, IT DOES NOT SET THE SELECTED DATETIME.
/>
<Button color="primary" className="ml-1" onClick={() => setcurrentDateTime(new Date())}>
    {"Immediate"}
</Button>

To use the Immediate button value i am using value={currentDateTime}. BUt this does not allow me to use the selected value

How to do this. Have new Date() value when i pressImmediate button. and have the selected value when i select a datetime

1

There are 1 answers

0
Sanket Shah On BEST ANSWER

This is happening because you haven't added the onChange event to your Datetime:

const [currentDateTime, setcurrentDateTime] = useState(null);

  return (
    <>
      <Datetime
        inputProps={{
          placeholder: "MM-DD-YYYY HH:mm",
          required: true
        }}
        viewMode="time"
        value={currentDateTime}
        onChange={setcurrentDateTime} // <--- You need to add onChange 
      />
      <Button
        color="primary"
        className="ml-1"
        onClick={() => setcurrentDateTime(new Date())}
      >
        {"Immediate"}
      </Button>
    </>
  );

Checkout this CodeSandbox:

Edit hopeful-cannon-wh1c9