2

I want to create a date range component that will fit both start and end dates into a single input. I tried using the example here https://reactdatepicker.com/#example-date-range-for-one-datepicker but it doesnt seem to display the endDate. I've set up a custom input to display both values, but I don't know how to update them both with a single onChange prop in my datePicker. I believe this has caused the component to fail with a RangeError: invalid time value.

const CustomDatePicker = (props) => {
  const {
    className,
    startDateId,
    endDateId,
    startLabel,
    endLabel,
    displayFormat,
    onStartDateChange,
    onEndDateChange,
    locale,
    startDate,
    endDate,
  } = props

const CustomInput = ({ value, onClick}) => {
    return 
     
        <input
          className="my-input"
          type="text"
          onClick={onClick}
          value={`${startDate} - ${endDate}`}
        />
      </div>
   
    )

return <DatePicker
            id={startDateId}
            selected={startDate}
            selectsRange
            startDate={startDate}
            endDate={endDate}
            placeholderText={placeholder}
            dateFormat={displayFormat}
            onChange={onStartDateChange}
            locale={selectLocale(locale)}
            customInput={<CustomInput />}
          />
}
Jub10
  • 183
  • 1
  • 2
  • 15

1 Answers1

6

If you follow the website you linked to, you can see that just when the input changes, it changes both the startDate as the endDate. This way you can keep both of them updated. So this would look like:

JSX:

          <DatePicker
            id={startDateId}
            selected={startDate}
            selectsRange
            startDate={startDate}
            endDate={endDate}
            placeholderText={placeholder}
            dateFormat={displayFormat}
            onChange={onChange}
            locale={selectLocale(locale)}
            customInput={<CustomInput />}
          />
         
         <input value={`${startDate} - ${endDate}`} />

Function:

const onChange = dates => {
    const [start, end] = dates;
    setStartDate(start);
    setEndDate(end);
}
  • Ahh Okay that makes sense thank you! What would I need to do about formatting? startDate and endDate aren't properly formatted, and if I supply the value prop, it only returns the formatted startDate. – Jub10 Feb 24 '21 at 19:10
  • 1
    You would have to either format the data when you use it or keep a copy that will have the formatted version. Here are some nice ways to format your dates: https://flaviocopes.com/how-to-format-date-javascript/ – Thaeke Hekkenberg Feb 24 '21 at 19:30