Simple Search In React Native
How to create a simple search feature using react native, react-navigation, and mysql
Step 1: Create the navigation screen/route for our search page
<Stack.Screen
name=”Search”
component={SearchScreen}
options={{
presentation:’modal’,
animation:’slide_from_bottom’
}}
/>
Step 2: Search Bar Header
My SearchScreen component looks like:
export default function ExploreSearch(){
const navigation = useNavigation()
const [query,setQuery] = useState("")
return(
<SafeAreaView style={styles.container}>
<View style={styles.inputHeader}>
<TextInput
onChangeText={(e)=>setQuery(e)}
style={styles.input}
defaultValue={query}
placeholder=”Search”
autoFocus
placeholderTextColor='white'
/>
<Pressable
style={styles.cancel}
onPress={()=>navigation.goBack()}
>
<Text>Cancel</Text>
</Pressable>
</View>
<SearchContentScrollContainer query={query}/>
</SafeAreaView>
)
}
const styles = StyleSheet.create({
container:{
flex:1,
alignItems:'center',
width:'100%,
paddingHorizontal:'5%'
},
inputHeader:{
width:'100%',
flexDirection:'row',
alignItems:'center',
justifyContent:'space-between',
padding:'5%'
},
input:{
height:40,
width:'80%',
borderWidth:1,
padding:10,
fontSize:16,
borderRadius:10
},
cancel:{
fontSize:16,
color:'white'
}
})
As we type into the textinput we are setting a query string which we are passing to another component SearchContentScrollContainer. This component will fetch the data and display it in a list. Lets build that now.
Step 3: Fetch and display data
Within our SearchContentScrollContainer we can listen for changes to the query string and query our database on each change like so:
const [data,setData] = useState<Content | null>(null)
useEffect(() => {
getResults()
}, [query]);
async function getResults(){
//however you talk to your server/db
const res = await callDatabase(query)
setData(res.data)
}
The way you talk to your database is likely different than how I am with this project (aws appsync and aurora rds) but the basic premise is to pass the string query to our backend to get data that matches. The most basic form of this is using SQL %LIKE% operator
See: SQL LIKE Operator
An example of what a query would look like:
select * from mytable where title LIKE '%query%' or description '%query%’ LIMIT some_limit
You can then use a Flatlist to display your data
This is a very basic way to set up a simple search feature and there are many ways to improve the setup. A few ways could be:
- Throttle the query so its not hitting the database on every single keystroke
- Add infinite scroll to Flatlist for a better user experience
- More advanced sql searching (this current approach may grab some irrelevant data)
Final result: