0

I am trying to return the first object of an array, how do I achieve this.

{ products && products.map((product,i)=>(
       <div key={i} >
          <h6>{product.name} - {product.category.name}</h6>
          <p className="mb-0"> {product.price} returns in {product.duration} months</p>
       </div>
   ))
 }
Gabriel Geelario
  • 227
  • 1
  • 2
  • 16
  • Don't use `products` (an array), set a variable `product` to `products[0]` and use that. – Heretic Monkey Oct 02 '20 at 12:42
  • As Heretic Monkey says, get the product item first let product = Array.isArray(products) && products.length > 0 && products[0], and avoid to get props this way products[0].name... – lissettdm Oct 02 '20 at 13:03

1 Answers1

0

If you are not interested in mapping the whole array, just getting first item, you can use index instead:

{ products && products[0] && (
       <div>
          <h6>{products[0].name} - {products[0].category.name}</h6>
          <p className="mb-0"> {products[0].price} returns in {products[0].duration} months</p>
       </div>)
   ))
 }

Note: By the way, [] is considered as truthy value in JS so you should use !!products.length instead of products

Piyush Rana
  • 631
  • 5
  • 8
szczocik
  • 1,293
  • 1
  • 8
  • 18