Search Function in React JS to display List with filtered items

To add a search function for a list in a React Component, we can follow these steps:
1. Create a new state variable to hold the search query.

2. Update the map function that renders the table rows to filter the array based on the search query.

3. Add an input field where users can enter their search query and update the state with the user’s input.

Example:

Here we have an array, adminProducts which needs to be filtered and displayed based on the query given for search function.

const [searchQuery, setSearchQuery] = useState(‘””);

A set variable “searchQuery” is used here to store the search query given by the user for search function.

<TextField

name = ‘search’

placeholder = ‘Search’

InputProps = {{

endAdorment : (

<IconButton>

<SearchIcon />

</IconButton>

value = {searchQuery}

onChange ={ (e) => setSearchQuery(e.target.value)}

/>

Another array is declared to store the filtered items obtained by filtering from the list.

const filteredAdminProducts = adminProducts.filter((contact) =>{

return (

searchQuery.trim() ===  ‘ ‘ ||    // if the search query is empty, show all items

Object.values(contact).some((value) = >

Value.toString().toLowerCase().includes(searchQuery.toLowerCase())

)

);

});

Finally use the filtered array to display the list:

<TableBody>

{filteredAdminProducts.map((contact, index) => (

<TableRow key ={ contact.id}>

{/* code to display the list */}

</TableRow>

))}

</TableBody>

Leave a Reply