$ git show sticky-tabs
Scroll-synced tabs
Category tabs stick to the top and the active tab follows the section you're scrolling through.
Inspired by Uber EatsFrom William Candillon’s “Can it be done in React Native?” series. The code here is a simplified rewrite for Reanimated 4 and 3.
This snippet uses APIs that didn’t change between versions, so the same code runs on Reanimated 4 and 3.
const y = useSharedValue(0);
const sectionsY = useSharedValue([]); // filled from each section's onLayout
const tabsX = useSharedValue([]), tabsW = useSharedValue([]); // from each tab's onLayout
const onScroll = useAnimatedScrollHandler(e => { y.value = e.contentOffset.y; });
const active = useDerivedValue(() => {
let i = 0;
for (let k = 0; k < sectionsY.value.length; k++) if (y.value >= sectionsY.value[k] - HEADER_H) i = k;
return i;
});
const indicator = useAnimatedStyle(() => ({
width: withSpring(tabsW.value[active.value] ?? 0),
transform: [{ translateX: withSpring(tabsX.value[active.value] ?? 0) }],
}));
// keep the active tab visible in the horizontal tab bar
useAnimatedReaction(() => active.value, i => scrollTo(tabBarRef, (tabsX.value[i] ?? 0) - 16, 0, true));
// tap a tab: listRef.current.scrollTo({ y: sectionsY.value[i] - HEADER_H })