onefinestay / react-daterange-picker

Other
563 stars 209 forks source link

Trigger event when PaginationArrow is clicked #200

Open balazsorban44 opened 6 years ago

balazsorban44 commented 6 years ago

I would like to trigger an event, and eventually change the state of my DaterangePicker's parent.

When I click on either forward or back, I want to update a month state to the currently active month in my app. This would allow me to fetch my overlapping dates for a given month which I can then send to DaterangePicker in the dateStates prop. I hope you can follow me...

How should I approach this?

AlanFoster commented 6 years ago

If I understand the question correctly, I believe you need to follow a similar approach to the sandbox snippet? i.e. Provide a callback to your component, and keep track of the date state and side effects in your top most component

Let me know how you get on :+1:

balazsorban44 commented 6 years ago

I solved it like so:

Made a PaginationArrow of my own:

const PaginationArrow = ({direction, onTrigger, onMonthChange}) =>
  <span
    className={`DateRangePicker__PaginationArrow DateRangePicker__PaginationArrow--${direction}`}
    onClick={() => {
      direction === "next" ?
        onMonthChange(1) :
        onMonthChange(-1)
      onTrigger()
    }}
  >
    {direction === "next" ? "►" : "◄"}
  </span>

Then in onMonthChange I change the month stored in my main component's state. onMonthChange and looks like this:

onMonthChange = direction => {
    let {month} = this.state
    month = month.clone().add(direction, "month").startOf("month")
    if (!month.isBefore(currentMonth)) {
      this.setState({month})
    }
  }

I also have disabled the dates before tomorrow, but then the PaginationArrow would not want to change to the current month. I solved it by passing the following minimumDate prop to DaterangePicker:

month.month() === moment().month() ? tomorrow : null

I am pretty sure there is an easier way, I just did not have time to examine DaterangePicker better how it really works, and without the lack of documentation, I have to search for answers in the source code. Also I just tried to find a dirty, but quick solution. I am on vacation now, but when I have some more time, I consider contributing to this repo a little bit more, because I think it has a big potential.