I am facing a strange error! I am trying to dynamically render products on my UI. When I have in my code:
render () {
const cart = this.props.cart
return (
<>
<PanelHeader size="sm" />
<div className="content">
<Row>
<Col xs={12}>
<Card>
<CardHeader>
<CardTitle tag="h4">Products List</CardTitle>
</CardHeader>
<CardBody>
<table class="table table-striped table-hover">
<thead>
<tr>
<th scope="col"><strong>#</strong></th>
<th scope="col"><strong>Name</strong></th>
<th scope="col"><strong>Code Item</strong></th>
<th scope="col"><strong>Quantity</strong></th>
<th scope="col"><strong>Price Total</strong></th>
</tr>
</thead>
{cart.length > 0 &&
<tbody>
<tr>
<th scope="row">1</th>
<td>{cart[0].title}</td>
<td>{cart[0].code}</td>
<td>{cart[0].quantity}</td>
<td>{cart[0].price}</td>
</tr>
</tbody>}
</table>
</CardBody>
</Card>
</Col>
</Row>
</div>
</>
)
}
}
It renders the first item, however if I try to choose the 3rd item: i.e. {cart[2].title} and so on gives my the error that "title" is not defined. Plus if i try to give [i] gives me an error that "i" is not defined! Any ideas how to solve it? Thank you in advance!
CodePudding user response:
If you need to render all your items in the cart array, then go with:
{cart.map(c =>
<tbody>
<tr>
<th scope="row">1</th>
<td>{c.title}</td>
<td>{c.code}</td>
<td>{c.quantity}</td>
<td>{c.price}</td>
</tr>
</tbody>}
CodePudding user response:
tbody goes outside the loop,then you need to add a key to each item.
<tbody>
{cart.length > 0 && cart.map((item, index) => (
<tr key={item.id}>
<th scope="row">{index}</th>
<td>{item.title}</td>
<td>{item.code}</td>
<td>{item.quantity}</td>
<td>{item.price}</td>
tr>))}
</tbody>