title: React - Slide fixed navbar up on scroll down and slide down on scroll up
body: <p><strong>tl;dr Scroll down for the solution that worked for me!</strong></p>
  
  <p>How to implement a slide up and down on a fixed navbar in react?</p>
  
  <p>What is the better approach using refs or using the componentDidMount lifecycle hook?</p>
  
  <pre><code>  hideNav = (navbar) =&gt; {
      const hide = () =&gt; {
        let lastScrollTop = 0;
        const currentScrollTop = navbar.scrollTop;
  
        // scroll down
        if (currentScrollTop &gt; lastScrollTop) {
        navbar.classList.add('hidden');
        } else {
        // scroll up
          navbar.classList.remove('hidden');
        }
        lastScrollTop = currentScrollTop;
      };
  
      window.addEventListener('scroll', hide);
    };
  </code></pre>
  
  <p>... further down in the render method:</p>
  
  <pre><code> render() {
        return &lt;Navbar ref={this.hideNav} /&gt;
  </code></pre>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>Solution:</p>
  
  <pre><code>class Navbar extends React.Component {
    state = {
      auth: false,
      slide: 0,  // How much should the Navbar slide up or down
      lastScrollY: 0,  // Keep track of current position in state
    };
  
    componentWillMount() {
      // When this component mounts, begin listening for scroll changes
      window.addEventListener('scroll', this.handleScroll);
    }
  
    componentWillUnmount() {
      // If this component is unmounted, stop listening
      window.removeEventListener('scroll', this.handleScroll);
    }
  
    handleScroll = () =&gt; {
      const { lastScrollY } = this.state; 
      const currentScrollY = window.scrollY;
  
  
      if (currentScrollY &gt; lastScrollY) {
        this.setState({ slide: '-48px' });
      } else {
        this.setState({ slide: '0px' });
      }
      this.setState({ lastScrollY: currentScrollY });
    };
  
     render() {    
      return (
        &lt;Navbar
          style={{
            transform: `translate(0, ${this.state.slide})`,
            transition: 'transform 90ms linear',
          }}
        /&gt;
       );
     }
   }
  </code></pre>
  
  <p>I haven't done any optimizations yet so it is recommended to throttle the event using requestAnimationFrame, setTimeout or customEvent. <a href="https://developer.mozilla.org/en-US/docs/Web/Events/scroll#Example" rel="noreferrer">Like here.</a></p>