Search code examples
reactjsreact-datepicker

When I use react-datepicker , Cannot read properties of undefined (reading 'value')


The UI appears, but the e.target.value cannot be read. Clicking on a calendar will result in an error.

There are two errors.I'll show you two errors through the picture first.

error1

error2

So, this is my code. The main component refers to this component.

import React, { useState } from "react";
import DatePicker from "react-datepicker";

import "react-datepicker/dist/react-datepicker.css";

const DatePick = () => {
  const [startDate, setStartDate] = useState("");

  const startDateHandler = (event) => {
    const gettodate = setStartDate(event.target.value);
    console.log(gettodate);
  };
  return (
    <DatePicker selected={startDate} onChange={startDateHandler} dateFormat={"yyyyMMdd"} showYearDropdown scrollableMonthYearDropdown />
  );
};

export default DatePick;

If I use

(date)=>setStartdate(date)

instead of handler, the value is undefined. how can i solve this problem ? i wanna get value.


Solution

  • yes, you can handle DatePicker value as (date)=>setStartdate(date).