Home > OS >  Get accurate value onChange event in react.js
Get accurate value onChange event in react.js

Time:03-03

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.

CodePudding user response:

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.

Edit late-brook-45k242

CodePudding user response:

You can print the date like,

goodsReadyBy?.date[0].toString()

Code to fetch the date string alone:

const App = () => {
  const [goodsReadyBy, setGoodsReadyBy] = useState();
  return (
    <div>
      <Flatpickr
        data-enable-time
        name="goodsreadyby"
        options={{
          enableTime: true,
          dateFormat: "Y-m-d H:i:s"
        }}
        onChange={(date) => {
          setGoodsReadyBy({ date });
        }}
      />
      <p> {goodsReadyBy?.date[0].toString()} </p>
    </div>
  );
};

Codesandbox:

Edit Example - React Hooks - useState (forked)

CodePudding user response:

Well your array only has one element so you can use the code below.

 onChange={(date) => {setGoodsReadyBy({date[0]})

It will give you the data in the format you need.

  • Related