or-yam
or-yam

Reputation: 41

Airbnb / react-dates | Is there a way to infinity scroll months instead of clicking next month?

I have a react-dates component in a web React app for mobile browsers. The component displays the month views vertically.

 <DayPickerRangeControllerWrapper
   orientation="vertical"
   numberOfMonths={3}
   verticalHeight={800}
 />

The component initialized to display 3 months. To move on to the next month, the user needs to click a button.

The goal is to implement an infinity scroll - display the next month by scrolling instead of clicking. For example, when the user scrolls down to the last displayed month, the next month (4th in this case) should render, and so on.

I went over the Docs and found onNextMonthClick function, but couldn't find a way to invoke it by scrolling.

I also tried to set the numberOfMonths to a large number (24) but it causes a delay in the component's render.

Is it possible to lazy load month by month by scrolling instead of clicking?

Upvotes: 3

Views: 1360

Answers (1)

noam steiner
noam steiner

Reputation: 4444

To render months by user scroll, you should add an event listener to the DOM, and update the number of months relative to scrolling.

For example:

import React from "react";
import ReactDOM from "react-dom";
import { Grid, Row } from "react-flexbox-grid";
import { DayPickerRangeController } from "react-dates";
import "react-dates/initialize";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { numberOfMonths: 0 };
  }

  componentDidMount() {
    window.addEventListener("scroll", this.handleScroll, { passive: true });
  }

  componentWillUnmount() {
    window.removeEventListener("scroll", this.handleScroll);
  }

  handleScroll = (event) => {
    this.setState((state, props) => ({
      numberOfMonths: state.numberOfMonths++
    }));
  };
  render = () => {
    return (
      <Grid>
        <Row>
          <DayPickerRangeController
            orientation="vertical"
            numberOfMonths={this.state.numberOfMonths}
            verticalHeight={800}
          />
        </Row>
      </Grid>
    );
  };
}


ReactDOM.render(<App />, document.getElementById("container"));

codesandbox demo

Upvotes: 2

Related Questions