Skip to content Skip to sidebar Skip to footer

How To Reveal A React Component On Scroll

I've created a React component for a fixed nav that I would like to remain hidden, until I scroll past a certain point on the page, then slides into view. Medium has a header simil

Solution 1:

React Way with vanilla JS jsfiddle;

don't forget to remove EventListener. In this example component will render if only it is neccessary

classTopBarextendsReact.Component {
    state = { isHide: false };

    hideBar = () => {
       const { isHide } = this.statewindow.scrollY > this.prev ?
       !isHide && this.setState({ isHide: true })
       :
       isHide && this.setState({ isHide: false });

       this.prev = window.scrollY;
    }

    componentDidMount(){
        window.addEventListener('scroll', this.hideBar);
    }

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

    render(){
        const classHide = this.state.isHide ? 'hide' : '';
        return<divclassName={`topbar ${classHide}`}>topbar</div>;
    }
}

Solution 2:

You could use a component such as react-headroom to do the heavy lifting for you. Or, you can still use waypoints in React, setting it up in the componentDidMountlifecycle method and removing it using componentWillUnmount.

Solution 3:

In the componentDidMount lifecycle hook, do the same thing as in the jQuery link you have given:

classNavbarextendsReact.component {

  let delta = 5;

  render() {
    return (
      <divref=header></div>
    );
  }

  componentDidMount() {
    $(window).scroll(function(event){
      var st = $(this).scrollTop();

      if(Math.abs(this.state.lastScrollTop - st) <= delta)
        return;

      if (st > lastScrollTop){
        // downscroll code// $(this.refs.header).css('visibility','hidden').hover ()this.setState({
          navbarVisible: false
        });
      } else {
        // upscroll code
        $(this.refs.header).css('visibility','visible');
        this.setState({
          navbarVisible: true
        });
      }
      lastScrollTop = st;
    }.bind(this));

  }
}

Solution 4:

I created a react component for this same exact need as I could not find any other implementations that matched what I needed. Even react-headroom did not give you something that would just scroll in after reaching a certain point on the page.

The gist is here: https://gist.github.com/brthornbury/27531e4616b68131e512fc622a61baba

I don't see any reason to copy the component code here. The code is largely based off of the react-headroom code but does less and is therefore simpler.

The component is the first piece of code, you could simply copy/paste then import it. After importing your code with the navbar would look something like this:

classMyScrollInNavBarextendsComponent {
    render() {
      return (
        <ScrollInNavscrollInHeight={150}><MyNavBar /></ScrollInNav>
      );
    }
}

Post a Comment for "How To Reveal A React Component On Scroll"