Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger animations in a React app based on the scroll position

Tags:

Let's say I need to add an element to the navbar when the user have scrolled past the header of the site. How can I do something like this in React without using jQuery?

like image 735
THpubs Avatar asked May 13 '17 07:05

THpubs


People also ask

How do you trigger a CSS animation on scroll in React JS?

Using the module react-animated-css-onscroll, we can trigger the animation whenever we scroll down to the component.

How do you trigger a scroll event in React?

To handle the onScroll event in React: Set the onScroll prop on an element or add an event listener on the window object. Provide an event handler function. Access relevant properties on the event or window objects.


1 Answers

You can do some thing like this: (this function was copied from my own react-sticky-dynamic-header that I created before: https://github.com/thinhvo0108/react-sticky-dynamic-header )

componentDidMount() {
    var h1 = parseInt(this.refs.header.offsetHeight);
    window.addEventListener('scroll', this._calcScroll.bind(this, h1));
}

componentWillUnmount() {
    window.removeEventListener('scroll', this._calcScroll)
}

_calcScroll(h1) {
    var _window = window;
    var heightDiff = parseInt(h1);
    var scrollPos = _window.scrollY;
    if (scrollPos > heightDiff) {
        // here this means user has scrolled past your header, 
        // you may rerender by setting State or do whatever
        this.setState({
            //stateKey: stateValue,
        });
    } else {
        // here the user has scrolled back to header's territory, 
        // it's optional here for you to remove the element on navbar as stated in the question or not
        this.setState({
            //stateKey: stateValue,
        });
    }
}

render() {
  return (
    <div ref="header">YOUR HEADER HERE</div>
  );
}

For a smooth animation when your element added or removed from the navbar, you can just add this into the element's CSS style:

#your-element{
  transition: opacity 0.3s ease-in;
}

You can try to install my library to see if it can extend your needs:

https://www.npmjs.com/package/react-sticky-dynamic-header

Feel free to post here some errors if any, thanks

like image 180
thinhvo0108 Avatar answered Sep 21 '22 10:09

thinhvo0108