In Reactjs, how can I add a search filter to my DataTable?
P粉447002127
2023-08-17 15:51:24
<p>I want to enhance my DataTable by adding search filter in ReactJS. I want the user to be able to search for a specific entry in the table. The goal is to allow users to easily search and find specific data in tables.How to implement this?</p>
<pre class="brush:php;toolbar:false;"><><ScrollView showsHorizontalScrollIndicator>
<View style={styles.root}>
<TouchableOpacity
style={[styles.button, styles.buttonOutline]}
onPress={handleBackButtonClick}
>
<Text style={styles.buttonOutlineText}>返回</Text>
</TouchableOpacity>
</View>
<TextInput
style={styles.searchInput}
placeholder="按客户搜索..."
/>
<DataTable style={styles.container}>
<DataTable.Header style={styles.tableHeader}>
<DataTable.Title>客户</DataTable.Title>
<DataTable.Title>地址</DataTable.Title>
<DataTable.Title>手机号码</DataTable.Title>
<DataTable.Title>车牌号码</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></pre>
Create a state to hold the search query and another state to store the filtered data:
Now add this function. First update the
searchQuery
status, then filter based on the giventext
parameter and set the result to thefilteredCustomers
status.This logic must be executed every time you enter in the search
TextInput
.Finally, just map by
filtredCustomers
instead ofdisplayedCustomers
: