3

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?

noam steiner
  • 4,034
  • 3
  • 27
  • 42
or-yam
  • 41
  • 1
  • 7

1 Answers1

2

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

noam steiner
  • 4,034
  • 3
  • 27
  • 42
  • Thank you Noam. It's an Interesting approach. But the problem with this solution is that a month added on each scroll event, my goal was to add a month when the user scroll down when reach to the last month. – or-yam Mar 11 '21 at 07:58