userden
userden

Reputation: 1683

How to display a header only after the user starts to scroll down? [React]

I'm using react, and I would like to display a header only after the user has scrolled down 150px on the page.

So when the user starts to scroll down, I would like a sticky header to appear. And again, when the user scrolls to the top of the page, the sticky header disappears.

<div className="container">
    // display this on top of the page:
    <JumbotronImage />
    // display this when user starts to scroll, sticky on top of the page
    <StickyHeader />
</div> 

I tried to do it with window.addEventListener('scroll'... , and I also tried https://github.com/fisshy/react-scroll but couldn't get it to work yet. Any suggestions?

Upvotes: 1

Views: 1416

Answers (2)

Saba
Saba

Reputation: 3666

I can think upon that your code would look as following. And the solution should fit like this.

export class App extends React.Component {
 componentDidMount() {
   ReactDOM.findDOMNode(this.stickyHeader).addEventListener('scroll', this.handleScroll.bind(this));
 }
 componentWillUnmount() {
   ReactDOM.findDOMNode(this.stickyHeader).removeEventListener('scroll', this.handleScroll.bind(this));
 }
 handleScroll() {
   // Add the logic here
 }
 render() {
   const {props} = this;

   return (
     <div className="container">
        // display this on top of the page:
        <JumbotronImage />
        // display this when user starts to scroll, sticky on top of the page
        <StickyHeader ref = {ele => this.stickyHeader = ele} />
     </div> 
   );
 }
}

You can refer this article which worked for me, http://blog.sodhanalibrary.com/2016/07/detect-scroll-direction-using-reactjs.html#.Wo0hq0nTS-4 to add logic inside handleScroll.

Upvotes: 2

manoj
manoj

Reputation: 297

I generally use this script for sticky header for my header with id="sticky"

$(window).scroll(function () {

    var iCurScrollPos = $(this).scrollTop();
    if (iCurScrollPos) {
     //#sticky put your element for which you want it to apply
        $('#sticky').addClass('stickyMenu');

    } else {
        $('#sticky').removeClass('stickyMenu');
    }

});

Add css for attached class

Upvotes: 1

Related Questions