I'm currently building an eCommerce website with an Add To Cart feature, I'm working within the Cart class. I'm using Redux -- the onDelete function is used for when there's a Delete button and I can remove a book from the current cart state by clicking it (calling onClick).
This is what I've been trying but it does not work and throws the error: "TypeError: Cannot read property 'onClick' of undefined".
You can see that I've passed this to the onClick function in the constructor so in the onClick property of the Button, I have simply passed the cartID into the onClick function:
Cart.js file
class Cart extends React.Component {
constructor() {
super();
this.onClick = this.onDelete.bind(this);
}
onDelete(_id) {
//
}
render() {
// if more than 1 item in cart array, then render the cart
// otherwise, render empty
if(this.props.cart[0]) {
return this.renderCart();
} else {
return this.renderEmpty();
}
}
renderEmpty() {
return (<div>Empty Cart</div>)
}
renderCart() {
const cartItemsList = this.props.cart.map(function(cartArr) {
return (
<Card key={cartArr._id}>
<Row>
<Col>
<h6>{cartArr.title}</h6>
</Col>
<Col>
<h6>USD {cartArr.price}</h6>
</Col>
<Col>
<h6>qty. goes here</h6>
</Col>
<Col>
<ButtonGroup style={{minWidth:'300px'}}>
<Button
variant = "default"
size = "small">
-
</Button>
<Button
variant = "default"
size = "small">
+
</Button>
<span> </span>
<Button
onClick = {this.onClick(cartArr._id)}
variant = "danger"
size = "small">
DELETE
</Button>
</ButtonGroup>
</Col>
</Row>
</Card>
)
})
return (
<Card>
{cartItemsList}
</Card>
)
}
}
I know that a part of this is due to the nature of the this keyword that I am passing to the onClick function. It works fine when I follow a tutorial and add the this keyword at the end of the cartItemList:
class Cart extends React.Component {
constructor() {
super();
this.onClick = this.onDelete.bind(this);
}
onDelete(_id) {
//
}
render() {
// if more than 1 item in cart array, then render the cart
// otherwise, render empty
if(this.props.cart[0]) {
return this.renderCart();
} else {
return this.renderEmpty();
}
}
renderEmpty() {
return (<div>Empty Cart</div>)
}
renderCart() {
const cartItemsList = this.props.cart.map(function(cartArr) {
return (
<Card key={cartArr._id}>
<Row>
<Col>
<h6>{cartArr.title}</h6>
</Col>
<Col>
<h6>USD {cartArr.price}</h6>
</Col>
<Col>
<h6>qty. goes here</h6>
</Col>
<Col>
<ButtonGroup style={{minWidth:'300px'}}>
<Button
variant = "default"
size = "small">
-
</Button>
<Button
variant = "default"
size = "small">
+
</Button>
<span> </span>
<Button
onClick = {this.onClick(cartArr._id)}
variant = "danger"
size = "small">
DELETE
</Button>
</ButtonGroup>
</Col>
</Row>
</Card>
)
})
return (
<Card>
{cartItemsList}
</Card>
)
}
}