Home > front end >  How do I count the amount of filtered items in my map?
How do I count the amount of filtered items in my map?

Time:04-29

    export const ProductList = (props) => {
     const [search, setSearch] = useState("");

I try create a const count, but dont work

     return (
        <div id="product-list">
          <header>
            <input 
              type="text"
              placeholder='Search...'
              onChange={(event)=>{
                setSearch(event.target.value);
              }}
            />

I need to dynamically show as per the filter products.length just show me the Total

        <strong>Product List ({products.length} items)</strong>
    
    
          </header>
          <table>
            <thead>
              <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Department</th>
                <th>Price</th>
              </tr>
            </thead>
            <tbody>
            {products.filter((val)=>{
              if(search == "") {

i try return count = 0

                return val
              } else if(val.name.toLocaleLowerCase().includes(search.toLocaleLowerCase())) {

And return count = val.length But count don't work

                 return val
              }
            }).map((val, key) =>{
              return <tr key={key}>
                  <td>{val.id}</td>
                  <td>{val.name}</td>
                  <td>{val.department}</td>
                  <td>{val.price}</td>
                </tr>;
            })}
            </tbody>
          </table>
        </div>
      )
    }

CodePudding user response:

You might be running into an issue here because you are performing the filter inline within your JSX. Instead, I suggest doing this outside of your JSX and then just showing the filtered products. See below for an example:

export const ProductList = (props) => {
   const [search, setSearch] = useState("");
   const [products, setProducts] = useState([ // ... your products array here ]);
   const [filteredProducts, setFilteredProducts] = useState([]);

   const onSearch = (val) => setSearch(val)

   useEffect(() => {
      const _filteredProducts = products.filter((val) => {
          if(search == "") {
              return val
          } else if(val.name.toLocaleLowerCase().includes(search.toLocaleLowerCase())) {

              return val
          }
      })
      setFilteredProducts(_filteredProducts)
   }, [search, products])

   ...

And then inside your JSX, you can just map over filteredProducts instead. Let me know if this works!

CodePudding user response:

you can do something like this

const [displayProduct, setDisplayProduct] = useState(products)

useEffect(() => {
  setDisplayProduct( products.filter(p => p.name.lowerCase().includes(search.toLowerCase())))
}, [search]) 



the you can use displayProduct.length and displayProduct.map to render your JSX

  • Related