Search code examples
javascriptreactjsonchange

Get accurate value onChange event in react.js


I'm trying to get the value of the date onChange:

<Flatpickr
   data-enable-time
   name="goodsreadyby"
     options={{
       minDate: date,
       enableTime: true,
       dateFormat:
        'Y-m-d H:i:s'
       }}
     onChange={(date) => {setGoodsReadyBy({date})
     }}/>

My problem is that I'm getting Array onChange event. Currently :

{date: Array(1)}
date: Array(1)
0: Sat Mar 05 2022 16:20:00  (Some Standard Time)
[[Prototype]]: Object
length: 1
[[Prototype]]: Array(0)
[[Prototype]]: Object

But I need the value like Sat Mar 05 2022 16:20:00 (Some Standard Time) only. How did I modify my code to get the exact value that I needed.


Solution

  • The 1st param of Flatpickr's onChange prop is selectedDates - an array of Dates (you can just access the first with selectedDates[0] and format it like you would with any Date).

    The 2nd is the dateStr - as formatted by the dateFormat option.

    export default function App() {
      return (
        <Flatpickr
          data-enable-time
          name="goodsreadyby"
          options={{
            enableTime: true,
            dateFormat: "Y-m-d H:i:s"
          }}
          onChange={(selectedDates, dateStr, instance) => {
            const firstDate = selectedDates[0];
            console.log({ firstDate, dateStr });
          }}
        />
      );
    }
    

    onChange will receive 3 arguments when called. These are:

    • selectedDates - an array of Date objects selected by the user. When there are no dates selected, the array is empty.
    • dateStr - a string representation of the latest selected Date object by the user. The string is formatted as per the dateFormat option.
    • instance - the flatpickr object, containing various methods and properties.

    Flatpickr docs

    Edit late-brook-45k242