Hide on scroll
The bar leaves when you scroll down and comes back when you scroll up.
How it works
Section titled “How it works”Animated.diffClampfollows the scroll distance between 0 and the height of the bar.- The bar is moved by
translateY, on the native driver. The list has the same height as top padding. - The search box itself needs nothing special.
Uses
Full source
Section titled “Full source”This is the code running in the phone. Copy it into your app.
import { useState } from 'react';import { Animated, Platform, StyleSheet, Text, View } from 'react-native';import Search from 'react-native-search-box';
const BAR_HEIGHT = 56;const GROUPS = ['Design team', 'Family', 'Book club', 'Landlord', 'Running group'];const CHATS = Array.from({ length: 40 }, (_, i) => ({ id: String(i), name: `${GROUPS[i % 5]} ${i + 1}` }));
function createBar() { const scrollY = new Animated.Value(0); // Overscroll (below 0) must not count as scrolling up. const distance = scrollY.interpolate({ inputRange: [0, 1], outputRange: [0, 1], extrapolateLeft: 'clamp', }); return { onScroll: Animated.event([{ nativeEvent: { contentOffset: { y: scrollY } } }], { useNativeDriver: Platform.OS !== 'web', }), translateY: Animated.multiply(Animated.diffClamp(distance, 0, BAR_HEIGHT), -1), };}
export default function HideOnScroll() { const [query, setQuery] = useState(''); const [bar] = useState(createBar); const reset = () => setQuery('');
return ( <View style={styles.screen}> <Animated.FlatList data={CHATS.filter((chat) => chat.name.toLowerCase().includes(query.toLowerCase()))} keyExtractor={(chat) => chat.id} contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled" onScroll={bar.onScroll} scrollEventThrottle={16} renderItem={({ item }) => ( <View style={styles.row}> <View style={styles.avatar} /> <View> <Text style={styles.name}>{item.name}</Text> <Text style={styles.message}>See you there</Text> </View> </View> )} /> <Animated.View style={[styles.bar, { transform: [{ translateY: bar.translateY }] }]}> <Search backgroundColor="#fff" titleCancelColor="#2563eb" inputHeight={BAR_HEIGHT - 18} inputBorderRadius={19} inputStyle={styles.input} containerStyle={styles.box} searchIconExpandedMargin={18} placeholderExpandedMargin={34} onChangeText={setQuery} onDelete={reset} onCancel={reset} /> </Animated.View> </View> );}
const styles = StyleSheet.create({ screen: { flex: 1, backgroundColor: '#fff', overflow: 'hidden' }, bar: { position: 'absolute', top: 0, left: 0, right: 0, height: BAR_HEIGHT, backgroundColor: '#fff' }, box: { marginTop: 4 }, input: { fontSize: 16, backgroundColor: '#f1f5f9', color: '#111' }, content: { paddingTop: BAR_HEIGHT }, row: { flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 16, paddingVertical: 10 }, avatar: { width: 48, height: 48, borderRadius: 24, backgroundColor: '#dbeafe' }, name: { fontSize: 16, fontWeight: '600', color: '#111' }, message: { color: '#6b7280', marginTop: 2 },});