How to reveal a React component on scroll

后端 未结 4 1609
谎友^
谎友^ 2021-02-04 04:38

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 s

4条回答
  •  名媛妹妹
    2021-02-04 04:56

    React Way with vanilla JS jsfiddle;

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

    class TopBar extends React.Component {
        state = { isHide: false };
    
        hideBar = () => {
           const { isHide } = this.state
    
           window.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 
    topbar
    ; } }

提交回复
热议问题