Advertisement
Guest User

Untitled

a guest
Aug 20th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. import React, { createContext, useState } from 'react';
  2.  
  3. export const CartContext = createContext();
  4.  
  5. export const CartContextProvider = (props) => {
  6. const [cart, setCart] = useState({items: []});
  7.  
  8. return(
  9. <CartContext.Provider value={[cart, setCart]}>
  10. {props.children}
  11. </CartContext.Provider>
  12. );
  13. }
  14.  
  15. const Item = ( {item} ) => {
  16.  
  17. const [cart, setCart] = useContext(CartContext);
  18.  
  19. const handleClick = e => {
  20. setCart(prevCartItems => ({...prevCartItems, items: items.push(item)}));
  21. }
  22.  
  23. console.log(cart.items);
  24.  
  25. return(
  26. <div className="item">
  27. <div className="product">
  28. <h2>{item.name} : ${item.price}</h2>
  29. <p>Category: {item.category}</p>
  30. </div>
  31. <button onClick={handleClick} className="add-to-cart">Add to Cart</button>
  32. </div>
  33. );
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement