Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a RangeError: Invalid Time Value when using React datepicker

I have set up a DatePicker component using the react-datepicker library and am passing it an initial date value calculated using today's date in the MM-DD-YYYY format.

However, when I load the page in React, I get

RangeError: Invalid Time Value

const AuthForm = ({ buttonText, formType, onAuth, history, ...props }) => {

  const startDate = new Date().toLocaleDateString();

  const initialStateSignup = {
      email : "",
      password : "",
      firstName: "",
      lastName: "",
      gender: "",
      dob: startDate
  };
    const [state , setState] = useState(formType === 'login' ? initialStateLogin : initialStateSignup);

  const handleChange = e => {
      const {name , value} = e.target;
      setState( prevState => ({
          ...prevState,
          [name] : value
      }))
  }
  ...
  return (
     <DatePicker
        placeholderText="Date of Birth"
        selected={state.dob}
        onChange={handleChange}
      />
  )

Where is this error coming from? I console logged the startDate and it looks valid to me, and this is the method I have seen documented in other threads for generating the start date.

like image 559
ipenguin67 Avatar asked Jul 16 '19 22:07

ipenguin67


2 Answers

According to this post https://github.com/Hacker0x01/react-datepicker/issues/1752 you most probably use old version of datepicker, that also may not be fully consistent with your React environment.

So check your react-datepicker version, if needed upgrade to 2+, and use this syntax:

const selected = moment(isoDateStr).toDate();

This is because react-datepicker before version 2 uses moment object date type directly and version 2+ uses javascript date type instead.

like image 149
Vlado Avatar answered Oct 15 '22 02:10

Vlado


Just pass to your DatePicker component dateFormat="MM-DD-YYYY" prop, with your desired format.

https://reactdatepicker.com/#example-7

<DatePicker
  dateFormat="MM-DD-YYYY"
  selected={this.state.startDate}
  onChange={this.handleChange} 
/>

P.D. You would like to use useReducer instead of useState in the case your state is an object.

like image 36
Adolfo Onrubia Avatar answered Oct 15 '22 01:10

Adolfo Onrubia