Search code examples
reactjsdate-range

Identify selected date range in react-date-range


I am using react-date-range plugin to select a date range.

import { DateRangePicker} from 'react-date-range';
import 'react-date-range/dist/styles.css';
import 'react-date-range/dist/theme/default.css';

enter image description here

Following function is used to handle the date range when a range is selected

    function handleSelect() {
            
    }

I have added the DateRangePicker like this

const selectionRange = {
    startDate: new Date(),
    endDate: new Date(),
    key: 'selection',
}

<div>
    <DateRangePicker
    ranges={[selectionRange]}
    onChange={handleSelect}/>
</div>

I want to make some operations on the selected date range in side the handleChange function. But I cannot find how to identify which date range is selected and the respective start and end dates.

In documentation onChange callback is described as enter image description here

But I cannot understand how to get these startDate and endDate parameters. Can someone help me to get this values.

Documentation: https://openbase.io/js/react-date-range/documentation


Solution

  • According to the documentation the onChange callback receives the ranges as an argument:

    import { DateRangePicker } from 'react-date-range';
    
    class MyComponent extends Component {
      handleSelect(ranges){
        console.log(ranges);
        // {
        //   selection: {
        //     startDate: [native Date Object],
        //     endDate: [native Date Object],
        //   }
        // }
      }
      render(){
        const selectionRange = {
          startDate: new Date(),
          endDate: new Date(),
          key: 'selection',
        }
        return (
          <DateRangePicker
            ranges={[selectionRange]}
            onChange={this.handleSelect}
          />
        )
      }
    }
    

    It should be an object that has a key selection which is itself an object that contains the startDate and endDate.