简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM