I am using the React DateTimePicker version 3.2.4 ("react-datetime-picker": "3.4.2")
and having a weird issue. I am using it in a form an auto-populating the form with the current date:
import React, { useState } from 'react';
import DateTimePicker from 'react-datetime-picker';
import config from '../../config/config';
import axios from 'axios';
function AddMeetingForm() {
const [meeting_name, setName] = useState('');
const [meeting_location, setMeetingLocation] = useState('');
const [date_time, setDateTime] = useState(new Date());
// A bunch of irrelevant code
const calendarChangeHandler = (event) => {
setDateTime(new Date(event));
};
return (
<div className='container all-center'>
<div
className='card text-center'
style={{ background: '#54c5f1', width: '385px', height: '700px' }}
>
<form onSubmit={mySubmitHandler}>
<h3 style={{ textDecoration: 'underline' }}>
Complete the Add Meeting Form and hit submit:
</h3>
<div className='grid-container'>
<div className='grid-item' style={{ width: '350px' }}>
// Irrelevant inputs
<label>*Meeting Date/Time</label>
<DateTimePicker
required
type='text'
name='date_time'
id='date_time'
onChange={calendarChangeHandler}
value={date_time}
style={{ backgroundColor: 'white', width: '466px' }}
/>
<label>Notes</label>
<textarea
id='notes'
name='notes'
onChange={myChangeHandler}
style={{
width: '100%',
marginBottom: '10px',
resize: 'vertical',
maxHeight: '200px',
}}
/>
</div>
</div>
<button
className='btn btn-primary'
type='submit'
id='addMeetingBtn'
style={{ marginTop: '40px' }}
>
Submit
</button>
</form>
</div>
</div>
);
}
export default AddMeeting Form
Everything works ok if the user uses the dropdown to change the day, month, year, or time. However, if the user want to manually change 1/21/2021 to 2/21/201 by typing '2' into the input box, the debugger shows that, rather than a new Date being based in the change event, something called a SyntheticBaseEvent
is passed which breaks the code when it tries to plug in an invalid date into the DateTimePicker input:
[![enter image description here][1]][1]
An error is then thrown: Uncaught Error: Invalid date: Invalid Date
. Why is this happening, and how can I catch or prevent this SyntheticBaseEvent
from occuring?
[1]: https://i.sstatic.net/vxpot.png
This issue seems to be caused by the event only picking up one part of the formatted date time. To resolve this I made the following changes, which resolves the issue.
<DateTimePicker
required
type='text'
name='date_time'
id='date_time'
onChange={(date) => setDateTime(date)}
selected={date_time}
value={date_time}
style={{ backgroundColor: 'white', width: '466px' }}
format='MM/dd/yyyy h:mm aa'
showTimeInput
timeIntervals={40}
showTimeSelect
/>