$ git show hide-header
Hide header on scroll
The top bar slides away as you scroll down and comes back as soon as you scroll up.
This snippet uses APIs that didn’t change between versions, so the same code runs on Reanimated 4 and 3.
const HEADER = 56;
const offset = useSharedValue(0); // 0 = shown, -HEADER = hidden
const lastY = useSharedValue(0);
const onScroll = useAnimatedScrollHandler({
onScroll: e => {
const y = Math.max(0, e.contentOffset.y); // ignore the iOS bounce at the top
const dy = y - lastY.value;
lastY.value = y;
// Move the header by the scroll delta, clamped between hidden and shown
offset.value = Math.min(0, Math.max(-HEADER, offset.value - dy));
},
onMomentumEnd: () => {
// Don't leave it half-way: snap to whichever is closer
offset.value = withTiming(offset.value < -HEADER / 2 ? -HEADER : 0, { duration: 150 });
},
});
const header = useAnimatedStyle(() => ({ transform: [{ translateY: offset.value }] }));
<Animated.ScrollView onScroll={onScroll} scrollEventThrottle={16} contentContainerStyle={{ paddingTop: HEADER }}>
{rows}
</Animated.ScrollView>
<Animated.View style={[styles.header, { height: HEADER }, header]} /> {/* position absolute, top 0 */}