score:12

Accepted answer

The onChange callback from react-datepicker looks like this:

onChange(date: Date | null, event: React.SyntheticEvent<any> | undefined): void;

So date potentially can be null. You have two options here:


1.) accept nullable date state in useState Hook:

const [startDate, setStartDate] = useState<Date | null>(new Date());

2.) only invoke setStartDate, when date is not null:

<DatePicker selected={startDate} onChange={date => date && setStartDate(date)} />

score:1

This works for me:

() => {
  const [startDate, setStartDate] = useState<Date|null>(new Date());
  return (
    <DatePicker selected={startDate} onChange={(date: Date | null) => setStartDate(date)} />
  );
};

score:2

I know I am late to join the party, I just got the DatePicker working. Following is the working code:

const [startDate, setStartDate] = useState<Date>(new Date());
<DatePicker
   selected={startDate}
   onChange={(date: Date) => setStartDate(date!)}
/>

score:8

Update for same issue in 2021

<DatePicker selected={startDate} onChange={(date: Date | null) => setStartDate(date)} />

Does the job


Related Query

More Query from same tag