Hide and replace sticky element on scrolling in a React way
— Tricky but interesting🍡
In a project I worked on, I faced a very interesting task, there is a sticky button at bottom of a mobile page, the requirement was to obtain an effect like this below: ✨
When the user scroll the page on mobile to a certain position, this button should not sticky at bottom anymore, in other words, it will start to follow the scrolling from this position.
This looks tricky, but after some analysis, I found out that it should be possible to achieve through the following steps, example below:
☘️ First, give this sticky button a visibility state and an Id so that we can locate it
☘️ Second, use the visible state to conditionally render this sticky button, something like:
☘️ Next Step, to track the position of the user scrolling instantly, we can add an event listener which should be added on component mount and removed on component unmount, let’s give it a name…