I'm looking to enhance my DataTable in React by incorporating a search filter.
I want users to be able to search for specific entries within the table.
The goal is to allow users to easily search and find specific data within the table. How to implement this?
<><ScrollView showsHorizontalScrollIndicator>
<View style={styles.root}>
<TouchableOpacity
style={[styles.button, styles.buttonOutline]}
onPress={handleBackButtonClick}
>
<Text style={styles.buttonOutlineText}>Back</Text>
</TouchableOpacity>
</View>
<TextInput
style={styles.searchInput}
placeholder="Search by customer..."
/>
<DataTable style={styles.container}>
<DataTable.Header style={styles.tableHeader}>
<DataTable.Title>Customer</DataTable.Title>
<DataTable.Title>Address</DataTable.Title>
<DataTable.Title>Mobile No.</DataTable.Title>
<DataTable.Title>Plate No.</DataTable.Title>
</DataTable.Header>
{displayedCustomers.map((customer, index) =>{
return(
<TouchableOpacity
key={index}
onPress={() => handleRowClick(customer)}
style={[ styles.row,
selectedRow && selectedRow.id === customer.id && styles.selectedRow]}
>
<DataTable.Row key={index}>
<DataTable.Cell>{customer.customer}</DataTable.Cell>
<DataTable.Cell>{customer.address}</DataTable.Cell>
<DataTable.Cell>{customer.mobileno}</DataTable.Cell>
<DataTable.Cell>{customer.plateno}</DataTable.Cell>
</DataTable.Row>
</TouchableOpacity>
)
})}
</DataTable>
<DataTable.Pagination
page={currentPage}
numberOfPages={Math.ceil(customers.length / itemsPerPage)}
onPageChange={handlePageChange}
/>
</ScrollView>
Create a state to hold the search query, and another one to store the filtered data:
Now add this function. First it updates
searchQuerystate, then it filters based on the giventextargment and set this result tofilteredCustomersstateYou want to execute this logic each time you type in the search
TextInputFinally, you just need to map through
filtredCustomersinstead ofdisplayedCustomers: