reactjsdatepicker

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.


Solution

  • 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.