5

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?

1
  • add eventlistener and rerender Commented May 13, 2017 at 8:34

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

Great. I can do what I want with this. Thanks!
Glad you had it working, for further issues related to React, feel free to ask me, If I can help I will try^^
Sure I will! Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.