Hide and replace sticky element on scrolling in a React way

MINI【xiaominzhu➿】
Geek Culture
Published in
4 min readJan 15, 2022

--

— Tricky but interesting🍡

最终,我们都将抵达终点 —We will all reach the end

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:

conditional render sticky button
conditional render scrolling button

☘️ 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…

--

--