Reputation: 1
Tried multiple attempts to bind but still unable to use method addItem to add a product to cart, App is my parent class, which im trying to pass the prop 'addItem'(Type: method) to Products, which will pass this method to Product(child of Products) and finally executed in Product
class App extends Component {
constructor(props) {
super(props);
this.state = {
cartitems: [],
}
this.addItem = this.addItem.bind(this);
}
addItem(item) {
this.setState({
cartitems : this.state.cartitems.concat([item]) });
...
<Route exact path='/Products' component={Products} addItem={this.addItem} />
}
Products is a class that fetches data from my database and pass it down to Product like so
<div className="row">
{items.map(item => <Product key={item.id} product={item} addItem={this.addItem} />)}
</div>
Finally, on Product i try to add the product to state cartitems whenever button is clicked,
<button className="btn btn-primary" onClick= {() => this.props.addItem.bind(this, this.props.product) }>Add to Cart</button>
Am very new to React so would appreciate it tons if someone could help! The title is the error name. Thank you!!!
Upvotes: 0
Views: 50
Reputation: 141
It's hard to tell without seeing your Product component, but I believe you're missing a reference to props in one reference to your method. I believe it should be
{items.map(item => <Product key={item.id} product={item} addItem={this.props.
addItem} />)}
Upvotes: 1