'React web app: 'Hide' elements of a table so those with value of zero are not shown

I have created an educational app to list products for an online store. I have created a table for these products, but I would like to hide those whose quantity have run out (i.e., hide the whole row when quantity=0).

I create the table from arrays in the state using array.map:

<table className="center-table" style={{border:'solid',}}>
      <thead className="has-text-black-bis" style={{backgroundColor:"#e6be8a"}}>
        <tr>
          <th >Product Name:</th>
          <th >Unit Price:</th>
          <th >Quantity Available:</th>
          <th >Buy!</th>
        </tr>
      </thead>
      <tbody className="has-text-black-bis">
        {this.state.indices.map((a) => (
          <tr className="rows">
            <td ><strong>{this.state.itemNames[a]}</strong></td>
            <td ><strong>{this.state.costs[a]} Wei</strong></td>
            <td ><strong>{this.state.quantities[a]}</strong></td>
            <td >
              Qty: <input type="text" className='table-input' name="inputs" value={this.state.inputs[a]} onChange={this.handleInputChange} />
              <button type="button" className='buy-btn' onClick={()=>this.buyItem(a)}> Buy!</button>
            </td>
          </tr>
        ))}
      </tbody>
    </table> 

I would imagine a for loop would work well, but I have not been able to implement this within JSX.



Solution 1:[1]

Just add a filter before the map method:

this.state.indices.filter((a) => a.quantity !== 0).map((a) => (...

You can also just go

this.state.indices.filter((a) => a.quantity).map((a) => (...

Because 0 is considered falsy in JS.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yogev D.