Search code examples
javascriptreactjsreact-datepicker

How can I add a date range with a single input to react-datepicker


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 />}
          />
}

Solution

  • 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);
    }