re: Hide menu when scrolling in React.js VIEW POST

VIEW PARENT COMMENT VIEW FULL DISCUSSION
 

About the top as a state key, If you could provide me with some way to test the efficiency I'll be thankful. I'll try it by myself also 😊

 

Hello Guim,

In Chrome Developer Tools under "Performance" tab you can record a new session. This will display your frame rate in idle state and animation/scroll action. But it will be really hard to see any difference with a fresh project. It will become obvious when you have a long list of DOM nodes, then document.getElement on each ~10ms event spawn (the duration between each scroll event execution, when the scrollHandler is executed) really effects the user experience and sometimes with some animations on top, the page becomes unusable.

About your code update, you can remove the "ref" since it is not used. And as a note that can help you some time in future, "refs" can't be used in componentDidMount/componentWillMount or any function triggered before rendering in the component lifecycle.

Also, please update your CSS. You should have two different classes. One that keeps your base component aspect, and one that will be used depending on component state to update your base style.


.navbar {
    width: 100%;
    padding: 10px;
    position: fixed;
    top: 0;
    left: 0;
    transition: top 0.6s;
}

.navbar--hidden {
    top: -50px;
}

Have a nice day!

Great contribution! Thanks. I updated the CSS and removed the ref too.

Perfect! As a final step, you could also change a bit the setState. Instead of having to write 3 times setState, you could do:

handleScroll = () => {
  const { prevScrollpos } = this.state;

  const currentScrollPos = window.pageYOffset;
  const visible = prevScrollpos > currentScrollPos;

  this.setState({
    prevScrollpos: currentScrollPos,
    visible
  });
};

It would be better to check if scroll direction (-Y or Y+) is the same with previous scroll direction. If it is the same, you don't have to update the state, because the component has the same position. By this I mean, if you already have the component hidden, and you keep scrolling down, you don't need to update its state.

And to be fair, I would add a debounce function wrapper to avoid calling this handler too many times (for performance reasons). Look into debounce method of "underscore" node modules. It's pretty easy to implement, and saves a lot of memory.

As always, simple problems have complex solutions. :)

code of conduct - report abuse