I’m building a shopping cart app, the app includes each item as a card component. I rendered these cards by mapping some dummy object data like this:
const Home = () => { const dummyData = [ { id: 1, title: 'tshirt', price: 10 }, { id: 2, title: 'coat', price: 20 } ] const RenderCards = () => { return ( dummyData.map( (d) => { return ( <Card key={d.id} title={d.title} price={d.price} handleAddToCart={handleAddToCart}/> ) } ) ) } const handleAddToCart = () => { // maybe access id and price here? } return ( <> <RenderCards /> </> ) }
and the Card
component being rendered:
const Card = ({id, title, price}) => { return ( <> <div key={id}> <p>{title}</> <p>{price}</> <button onClick={handleAddToCart}>Add to cart</button> </div> </> ) }
Now on click of the button in each card, I’d like to send the data (the id of the card and the price of the item) back to the parent Home
component. Say 2nd card is clicked, I want to have access to id
and price
in Home
.
EDIT:
Maybe I didn’t make myself clear, I’d like to access the clicked card’s price and id in handleAddToCart
function.
Advertisement
Answer
You can either pass the handler down and have the child pass the details to it, like this:
items.map(item => <Item addToCart={addToCart} {...item} />) const Item = ({ id, name, addToCart }) => <div> {name} <button onClick={() => addToCart(id)}>Add to Cart</button> </div>
Or pass down a values-included callback like this:
items.map(item => <Item addToCart={() => handleAddToCart(item.id)} {...item} />) const Item = ({ id, name, addToCart }) => <div> {name} <button onClick={addToCart}>Add to Cart</button> </div>