3

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

Ruchira Nawarathna
  • 1,137
  • 17
  • 30
  • You will get the selected date range in its handler function `handleSelect(date){ console.log(date); // native Date object }` – Mayank Pandeyz Oct 09 '20 at 09:35

2 Answers2

2

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.

trixn
  • 15,761
  • 2
  • 38
  • 55
0

My solution is:

const onChange = (item) => {
    if (item.selection.endDate !== item.selection.startDate) {
        console.log(item);
        setIsPopoverOpen(false);
    }
    setRange([item.selection]);
}
Think
  • 1