Filter a list
Typing filters a local list, clearing restores it. “ha noi” finds “Hà Nội”.
How it works
Section titled “How it works”onChangeTextstores the query; the list is filtered while rendering.- Without
valuethe clear and Cancel buttons do not callonChangeText, soonDeleteandonCancelreset the query. keyboardShouldPersistTaps="handled"on the list lets a row take the first tap.
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 { FlatList, StyleSheet, Text, View } from 'react-native';import Search from 'react-native-search-box';
const CITIES = 'Amsterdam,Bangkok,Barcelona,Berlin,Buenos Aires,Cairo,Cape Town,Đà Nẵng,Dublin,Hà Nội,Helsinki,Istanbul,Jakarta,Kyoto,Lima,Lisbon,London,Madrid,Mexico City,Montreal,Nairobi,New York,Oslo,Paris,Prague,Rome,Sài Gòn,Seoul,Singapore,Sydney,Taipei,Tokyo,Vienna,Warsaw,Zurich'.split( ',', );
/** Case and accents do not matter: "ha noi" finds "Hà Nội". */const normalize = (text: string) => text .normalize('NFD') .replace(/[\u0300-\u036f]/g, '') .replace(/đ/gi, 'd') .toLowerCase();
export default function Basic() { const [query, setQuery] = useState(''); const results = CITIES.filter((city) => normalize(city).includes(normalize(query.trim()))); const reset = () => setQuery('');
return ( <View style={styles.screen}> <Search backgroundColor="#e5e5ea" titleCancelColor="#007aff" placeholder="City" inputHeight={36} inputBorderRadius={10} searchIconCollapsedMargin={34} searchIconExpandedMargin={14} placeholderExpandedMargin={30} inputStyle={styles.input} onChangeText={setQuery} onDelete={reset} onCancel={reset} /> <FlatList data={results} keyExtractor={(city) => city} keyboardShouldPersistTaps="handled" renderItem={({ item }) => <Text style={styles.row}>{item}</Text>} ListEmptyComponent={<Text style={styles.empty}>No city matches “{query}”.</Text>} /> </View> );}
const styles = StyleSheet.create({ screen: { flex: 1, backgroundColor: '#fff' }, input: { fontSize: 16, color: '#111' }, row: { paddingVertical: 13, marginLeft: 16, fontSize: 16, color: '#111', borderBottomWidth: 1, borderColor: '#eee', }, empty: { padding: 32, textAlign: 'center', color: '#6b7280' },});