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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With