Search code examples
reactjsreact-datepicker

Get React DatePicker date value in onChange


I'm using react-datepicker, and I'm unable to get the actual date in onChange.

This is my component :

import DatePicker from "react-datepicker";

const DatePick = () => {
  return (
    <DatePicker
      locale="fr"
      dateFormat="dd/MM/yyyy"
      onChange={(date) => {
        console.log(date);
      }}
    />
  );
};

export default DatePick;

In console.log I'm getting this kind of string Thu Dec 09 2021 00:00:00 GMT+0100 (heure normale d’Europe centrale).

I need to get the date as dd-MM-yyyy in onChange or a date that I can format and use later in a form and submit its value.


Solution

  • Use Below code , it will work like a charm

    const [Cdate, setDate] = useState(new Date().toLocaleDateString('fr-FR'));
    return (
     <>
      <DatePicker
        dateFormat="dd/MM/yyyy"
        value={Cdate}
        onChange={(date) => {
          const d = new Date(date).toLocaleDateString('fr-FR');
          console.log(d);
          setDate(d);
        }}
      />
     </>
    );
    

    stackblitz link: https://stackblitz.com/edit/react-nov8it?file=src/App.js