Reputation: 11
I am new to React. Trying to make a shopping cart where I have an Array of data as items for sale which is being looped through and displayed on DOM as Cards. I want to know which item in the array the user clicks so I can add that to my cart.
Here is my Code. Please ask any questions if I'm being vague
import React, { Component } from "react";
import "./css/Card.css";
import Data from "./DummyData";
class Card extends Component {
state = {
zoom: false,
NumberOfItemsInCart: 0,
itemsInCart : [] ,
selectedCard : ''
};
render() {
// Method Target the selected Card and Zoom it
const handleCheck = (e) => {
this.setState({
zoom : true,
selectedCard : ?????
})
};
const addItem = () => {
this.props.addItemToCart(this.state.NumberOfItemsInCart)
//////////// ADD THE NAME OF THE ITEM SELECTED in Cart Array /////////
}
const DeleteItem = () => {
this.props.DeleteItemFromCart(this.state.NumberOfItemsInCart)
//////////// DELETE THE NAME OF THE ITEM SELECTED From Aray /////////
}
return (
<div className="band">
{Data.map((item, index) => {
return (
<div key={item.id} className="items" onClick={handleCheck} index={this.state.index}>
<div className="thumb">{item.title} </div>
<img className="item-images" src={item.img} alt={item.title} />
<div className="item-footer"> Price ${item.price}/lb </div>
<button className="btn btn-details" > Details </button>
<button onClick={addItem} className="btn btn-danger"> + </button>
<button onClick={ DeleteItem} className="btn btn-danger"> - </button>
</div>
);
})}
</div>
);
}
}
export default Card;
Upvotes: 0
Views: 496
Reputation: 505
or you can use
onClick={this.handleCheck.bind(this,id)}
handleCheck(){
this.setState({
zoom : true,
selectedCard : id
})
}
Upvotes: 0
Reputation: 9063
You can pass the id as an argument, change
onClick={handleCheck}
to
onClick={() => handleCheck(item.id)}
and handleCheck()
to
const handleCheck = (id) => {
this.setState({
zoom : true,
selectedCard : id
})
};
Upvotes: 1