Search functionality in React Js
import React, {useState } from 'react';
const ProductList = () => {
const [searchInput, setSearchInput] = useState('');
const handleSearch = (e) => {
setSearchInput(e.target.value);
}
const productArray = [
{
id:1,
name: 'Samsung',
image: "a.jpg",
price: 500,
},
{
id:2,
name: 'Nokia',
image: "a.jpg",
price: 100,
},
{
id:3,
name: 'Realme',
image: "a.jpg",
price: 300,
},
{
id:4,
name: 'Apple',
image: "a.jpg",
price: 200
},
];
const filteredSearchInput = !searchInput ? productArray : productArray.filter(res=>
res.name.toLowerCase().includes(searchInput.toLowerCase()));
return (
<>
Filter Product:{" "}
<input type="search" value={searchInput} onChange={handleSearch} />
<ul>
{filteredSearchInput ? filteredSearchInput.map(res =>
(
<li key={res.id}>
{res.name} | <b>{res.price}</b>
</li>
)
) : productArray.map(res =>
(
<li key={res.id}>
{res.name} | <b>{res.price}</b>
</li>
)
)}
</ul>
</>
)
}
export default ProductList;