How to Show and Hide Content Scrolling Up and Down in React Native with Reanimated
In this article, we will create something similar to Medium’s app article action that appears when you scroll up and disappears when you scroll down a technique which we call “reveal on scroll” and also add a simple animation to it. So, let’s get started.
We can now scroll, but the article action bar isn’t disappearing yet. We’ll make use of the useAnimatedScrollHandler
which returns an event handler reference.
First, write the logic to check whether the user is scrolling up or down.
We defined a scrollHandler
and attached it to the ScrollView.
Notice that I have changed ScrollView
to Animated.ScrollView
and View
to Animated.View
. Wrapping the component in Animated
allows the handler to trigger correctly. Also, notice the useSharedValue
hook we are using to store values. The hook carries data, provides a way to react to changes, and drives animations.
Now that we can detect when the user is scrolling up or down, we can hide and show the article action bar. We will make use of the translate style property to achieve that. While the user is scrolling up, thetranslateY
property should have a value of 0 and 100 when scrolling down.
There’s a new hook added, useAnimatedStyle.
We’re going to use the useAnimatedStyle
hook to spawn a worklet. This hook returns an object style, we can then add the style to an element. In the code above, I added the style object returned by useAnimatedStyle
to the article action bar.
I also use withTiming
function to achieve the animation. Without the function, the element won’t animate.
And that’s it. You can check the snackbar and the GitHub repository.
Level Up Coding
Thanks for being a part of our community! More content in the Level Up Coding publication.
Follow: Twitter, LinkedIn, Newsletter
Level Up is transforming tech recruiting ➡️ Join our talent collective