4

I have built a React component which is suppose to call the function on window scroll event.

I would like to call the function, "getCards('default'), when the user scroll to 90% of the scroll height.

The component looks as shown in below:

class Home extends React.Component {

  constructor(props) {
    super(props);
    this.handleScroll = this.handleScroll.bind(this);
  }

  componentDidMount() {
    // test
    this.props.getCards('default');
    window.addEventListener('scroll', this.handleScroll);
  }

  handleScroll(event) {
    console.log('scroll event');
  }

Could anyone help me achieve this?

Thank you.

Eunicorn
  • 601
  • 6
  • 16
  • 29

2 Answers2

4

You have to work with your component, please refer to this code:

class Home extends React.Component {

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    // test
    this.props.getCards('default');
  }

  render() {
    return (<div onScroll={this.handleScroll}>...</div>)
  }

  handleScroll(event) {
    var heightBound = window.height * 0.8
    if (heightBound > window.scrollY) {
        // Probably you want to load new cards?
        this.props.getCards(...);
    } 
  }

The scroll event must be placed inside your component and binded using onScroll evt. The handler will check for percentage of used screen size and will load others elements if the lower bound limit is reached.

I hope this can help :)

Roberto Conte Rosito
  • 2,080
  • 12
  • 22
  • 1
    Works great, thanks. A comment so others don't make the same mistake as me: it's an uppercase S (onScroll). Also, to use the class methods inside handleScroll remember to bind it (if it's not already in the constructor): `onScroll={this.handleScroll.bind(this)}` – Alvaro Sep 11 '18 at 11:11
1

I've got a similar problem and nothing with onScroll work to me.

constructor(props) {
  super(props);
  window.addEventListener('scroll', this.handleScroll, true);
}

handleScroll = (event) =>  { 
  // Your code
}

https://gist.github.com/koistya/934a4e452b61017ad611

monteirobrena
  • 2,562
  • 1
  • 33
  • 45