Home > other >  React search bar filter after click
React search bar filter after click

Time:12-27

I have a filter to search the product but it will search directly after I type the product name.

My Code

    const [searchTerm, setSearchTerm] = useState("");
    const [product, setProduct] = useState([]); 

    const displayProduct = product
    .filter((product)=>{
        if (searchTerm == ""){
            return product
        }else if(product.productName.replaceAll(/\s/g,'').toLowerCase().includes(searchTerm.toLowerCase().replaceAll(/\s/g,''))){
            return product
        }
    })
    .slice(pagesVisited,pagesVisited   productPerPage)
    .map(product => {
        return(
            <div className='imageContainer ' key={product.id}>
                <img src={PopularOne} className="image"/>
                <div className='productName'>
                <Link style={{ textDecoration:'none' }} to="/productsDetails" state={{ product:product }}>{product.productName}</Link>
                </div>
                <div className='productPrice'>
                <h3 >RM{product.productPrice}</h3>
                </div>
            </div>   
        )
    })

   <div>
     <input className='filterInput' onChange={event => 
     {setSearchTerm(event.target.value)}}></input>
     <button className='filterSearchButton'>Search</button>
   </div>

How do I let it filter after I click on a button?

CodePudding user response:

I have added onClick to button

onClick call handleFilter to filter data

also added new seState to set filtered data

const [searchTerm, setSearchTerm] = useState("");
const [displayProduct, setDisplayProduct] = useState(product || []);

const handleFilter = () => {
  const _displayProduct = product
  .filter((product)=>{
      if (searchTerm == ""){
          return product
      }else if(product.productName.replaceAll(/\s/g,'').toLowerCase().includes(searchTerm.toLowerCase().replaceAll(/\s/g,''))){
          return product
      }
  })
  .slice(pagesVisited,pagesVisited   productPerPage)
  .map(product => {
      return(
          <div className='imageContainer ' key={product.id}>
              <img src={PopularOne} className="image"/>
              <div className='productName'>
              <Link style={{ textDecoration:'none' }} to="/productsDetails" state={{ product:product }}>{product.productName}</Link>
              </div>
              <div className='productPrice'>
              <h3 >RM{product.productPrice}</h3>
              </div>
          </div>   
      )
  })
  setDisplayProduct(_displayProduct);
}

<div>
 <input className='filterInput' onChange={event => 
 {setSearchTerm(event.target.value)}}></input>
 <button className='filterSearchButton' onClick={handleFilter}>Search</button>
</div>

  • Related