React-dates: How to prevent DateRangePicker from closing on outside click?

Created on 21 Aug 2019  路  3Comments  路  Source: airbnb/react-dates

Hi,
I'd like to switch off the default behavior of the DateRangePicker to close and save the dates when clicking outside, how would I do that?

Expected behavior for my scenario: it is possible to close the datepicker only when clicking a button.

Most helpful comment

@maciej-w you can modify onFocusChange method of DateRangePicker:

...
<DateRangePicker
  startDate={this.state.startDate} 
  startDateId="your_unique_start_date_id" 
  endDate={this.state.endDate} 
  endDateId="your_unique_end_date_id" 
  onDatesChange={({ startDate, endDate }) => this.setState({ startDate, endDate })} 
  focusedInput={this.state.focusedInput} // PropTypes.oneOf([START_DATE, END_DATE]) or null,
  onFocusChange={focusedInput => {
    // Do not apply if it is null
    if (focusedInput) {
      this.setState({ focusedInput });
    }
  }}
/>

And for your close button you can set state focusedInput to null by click:

<button onClick={() => this.setState({ focusedInput1: null })}>Close picker</button>

All 3 comments

@maciej-w you can modify onFocusChange method of DateRangePicker:

...
<DateRangePicker
  startDate={this.state.startDate} 
  startDateId="your_unique_start_date_id" 
  endDate={this.state.endDate} 
  endDateId="your_unique_end_date_id" 
  onDatesChange={({ startDate, endDate }) => this.setState({ startDate, endDate })} 
  focusedInput={this.state.focusedInput} // PropTypes.oneOf([START_DATE, END_DATE]) or null,
  onFocusChange={focusedInput => {
    // Do not apply if it is null
    if (focusedInput) {
      this.setState({ focusedInput });
    }
  }}
/>

And for your close button you can set state focusedInput to null by click:

<button onClick={() => this.setState({ focusedInput1: null })}>Close picker</button>

@mmarkelov that works, but it keeps the focus on end date. Change that listener to the below, if you want to have a more consistent behavior (resetting it to start date after selecting end date):

import { START_DATE } from 'react-dates/constants';

...

onFocusChange={focusedInput => {
  // Do not apply if it is null
  if (focusedInput) {
    this.setState({ focusedInput });
  } else {
    this.setState({ focusedInput: START_DATE });
  }
}}

Can you post somewhere an example of this running? I'm fighting with this issue where no matter where I click the calendar closes. Additionally when I click on a drop down option the calendar also closes.

Was this page helpful?
0 / 5 - 0 ratings