EDGECRUSHER
EDGECRUSHER

Reputation: 83

React render array of objects

I have trouble rendering products array to my page and nothing really shows. I have no idea what to do with it and ive tried it on lesser scale with just li and it worked, but rendering more complex stuff is a problem for me

constructor(props) {
    super(props)
    var products = [
        { name: "Motorhead glasses", price: 300, amount: 1 },
        { name: "Judaspriest glasses", price: 499, amount: 1 }
    ]
    this.state = {products:[]}


}

render() {
    return (
        <div className="order">
            { this.state.products.map(function(product, i) {
                    <div className="order-product" key={i}>

                        <h3 className="order-product_name">{product.name}</h3>
                        <div className="order-product_amount">

                                <p>{product.amount}</p>

                            </div>
                        </div>
                        <div className="order-product_price"><span className="l">Price</span><span className="right">${product.price}</span></div>
                    </div>
                })
            }

            <div className="order-summary">
                <h3>Order Summary</h3>
                <div className="order-summary_summary">
                    <p>Subtotal <span className="price">$300</span></p>
                    <p>Shipping <span className="price">$20</span></p>
                    <hr />
                    <p>Total <span className="price">$320</span></p>
                </div>
            </div>
        </div>

    )
}

}

Upvotes: 1

Views: 1318

Answers (1)

lunochkin
lunochkin

Reputation: 784

It's because you are not returning anything from inner function. You should add return:

{this.state.products.map(function(product, i) {
  return <div className="order-product" key={i}>

      <h3 className="order-product_name">{product.name}</h3>
      <div className="order-product_amount">

              <p>{product.amount}</p>

          </div>
      </div>
      <div className="order-product_price"><span className="l">Price</span><span className="right">${product.price}</span></div>
  </div>
})}

And also you have empty products array in state, as was mentioned in comments.

Replace it to this: this.state = {products: products}

Upvotes: 2

Related Questions