Search code examples
javascriptreactjsreact-hooksreact-datepicker

Reactjs Hook onChange with react-datepicker, invalid time value error


im new to react hooks and i tried to convert react-datepicker from class to function with hooks. The problem is when i trigger the onChange will show (RangeError: Invalid time value), but default "selected" start date is rendering fine. Can this be done with hooks?

 import React, { useState, Fragment } from 'react';
 import Datepicker from 'react-datepicker';

 const Example = () => {

 const [startDate, setStartDate] = useState(new Date());

 const handleChange = date => {
   setStartDate({ startDate: date });
  }

 return (
   <Fragment>
    <Datepicker
     selected={startDate}
     onChange={handleChange}
    />
   </Fragment>
 )
}

export default Example;

i expect the startDate state is changed without "RangeError: Invalid time value".


Solution

  • The problem is that you are not inserting a date into the state but an object rather.

    change:

    setStartDate({ startDate: date });
    

    to:

    setStartDate(date);