Using React’s useEffect
hook.
In this article we will look at how to achieve the scroll-sensitive header very much so like the Medium header that seems to disappear as you scroll down and magically re-appear once you scroll upwards anticipating that you may want to access the header once more.
First things first, the CSS responsible for the motion is heavily inspired by the Evanto tuts+ codepen that you can find here. Be sure to check that out as well.
Now to get started, the first order of business is to setup the useEffect
hook as well as the useState
hook that will have a state value that helps the useEffect
hook determine whether or not we are scrolling upwards, then respond appropriately.
Moreover, do not forget to pass the headerRef
as a reference to the Header
component that you imported in.
At this point, we also have the introduction of the currentScroll
state that we will use to indicate where in the page we are now with regards to the vertical axis and the difference between that and where we were not so long ago in order to be able to determine which direction we are scrolling in, either upwards or downwards .Either of which will elicit certain behaviours to be exhibited by the header.
As for upward scrolling we will append the scroll-up
class that will push up the header upwards effectively removing it from view in order to allot more room on the page to the contents of the page. While during downward scrolling we will append the scroll-down
class that will make the header stick to the top of the page and slide it into position from previous invisibility.
And lastly, to tie all this together. Within the useEffect hook our callback method that we will run every time there is a change to the window.pageYOffset
that we have conveniently stored in the currentScroll
state will help us determine which direction we are scrolling to .i.e if our new offset is larger than our previous one that means we are scrolling downwards and vice versa.
And that should be all. Hope this helps for those trying to achieve that effect.