$ git show scroll-top-fab
Scroll-to-top button
A floating arrow springs up once you have scrolled down a way, and scrolls you back to the top when tapped.
// Unchanged in Reanimated 4: scroll-driven, so the button still reads a shared value
const ref = useAnimatedRef();
const scrollY = useSharedValue(0);
const onScroll = useAnimatedScrollHandler((e) => { scrollY.value = e.contentOffset.y; });
const shown = useDerivedValue(() => withSpring(scrollY.value > 400 ? 1 : 0, { damping: 15, stiffness: 200 }));
const fab = useAnimatedStyle(() => ({
opacity: shown.value,
transform: [
{ translateY: (1 - shown.value) * 24 },
{ scale: 0.6 + 0.4 * shown.value },
],
}));
const toTop = () => ref.current?.scrollTo({ y: 0, animated: true });
<View style={{ flex: 1 }}>
<Animated.ScrollView ref={ref} onScroll={onScroll} scrollEventThrottle={16}>
{content}
</Animated.ScrollView>
<Animated.View style={[styles.fab, fab]}> {/* absolute, right 20, bottom 32, 48 x 48 circle */}
<Pressable onPress={toTop} hitSlop={8}><ArrowUpIcon /></Pressable>
</Animated.View>
</View>