use Waypoint with React to execute a function after scroll

4.4k Views Asked by At

I have a counter component that counts up to a number on the page. I need it to run ones the user scrolls to that point on the page. How do I do that with Waypoint? Or is there another solution?

import React, { Component } from 'react';
import Waypoint from 'react-waypoint';

var Counter2017 = React.createClass({

   getInitialState: function() {
      return {visionElapsed: 0};
   },
   tick: function() {
      if (this.state.visionElapsed < 125) {
      this.setState({visionElapsed: this.state.visionElapsed + 1});
      }
   },
   componentDidMount: function() {
      this.interval = setInterval(this.tick, 15);
   },
   componentWillUnmount: function() {
      clearInterval(this.interval);
   },
   render: function() {
      return (
         <span>{this.state.visionElapsed}</span>
      );
   }
});

export default Counter2017;
3

There are 3 best solutions below

0
jmac On

You can try with componentDidUpdate(prevProps, prevState). In that method you will get notified about change in state. Invoke there what you need when user reaches the point.

More in docs: https://facebook.github.io/react/docs/react-component.html#componentdidupdate

1
Fleezey On

You insert your waypoint where you want it to be (it is a DOM element).

So you would have something that looks like this:

<div>
  <AnyComponents />
  <Waypoint
    onEnter={() => this.interval = yourInterval}
  />
</div>

Of course you can check if there is already an interval so you don't override it. You can also set an onLeave props on the Waypoint component. I suggest you to read about it here: https://github.com/brigade/react-waypoint

0
gualopezb On

The best you can do is using the react-waypoint lib