Home > Back-end >  How to iterate on an array and print table in react
How to iterate on an array and print table in react

Time:07-22

I want to iterate over an array and make a table row with its elements.
The coinlist is an array of object containing coin symbol and price. Is there any way to print table row with map function.

      <tbody>
            {coinlist.map((coin) => {
              return {
               
                 <tr>
                        <td>{coin.symbol}</td>
                        <td>{coin.price}</td>
                 </tr> 
            } })} 
        </tbody>

CodePudding user response:

    <table>
      <tr>
        <th>Symbol</th>
        <th>Price</th>
       
      </tr>
     {coinlist.map(coin)=>(
 <tr>
        <td>{coin.symbol}</td>
        <td>{coin.price}</td>
       
      </tr>
))}
     
    </table>

CodePudding user response:

If you want to print out the object fields which make up the table row you can either console.log the entire object which makes up the row or each individual field. Something along the lines of:

<tbody>
    {coinlist.map((coin) => {
        console.log(coin); // see the entire coin object
        console.log(`symbol: ${coin.symbol} price: ${coin.price}`); // see individual fields of interest
        return {  
            <tr>
               <td>{coin.symbol}</td>
               <td>{coin.price}</td>
             </tr> 
         } 
     })} 
</tbody>

Hopefully that helps

  • Related