A Simple cart context File:
import React, { useState } from "react";
const CartContext = React.createContext({
showCart: () => {},
hideCart: () => {},
isCartVisible: false,
});
export const CartProvider = (props) => {
const [cartStatus, setCartStatus] = useState(false);
const handelShowCart = () => {
setCartStatus(true);
};
const handelHideCart = () => {
setCartStatus(false);
};
const value = {
showCart: handelShowCart,
hideCart: handelHideCart,
isCartVisible: cartStatus,
};
return (
<CartContext.Provider value={value}>{props.children}</CartContext.Provider>
);
};
export default CartContext;
Implementing Cart context provide in APP js file.
import CartContext, { CartProvider } from "./Context/CartContext";
const App = () => {
const ctx = useContext(CartContext);
return (
<CartProvider>
{ctx.isCartVisible && <Cart />}
<Header />
<Meals />
</CartProvider>
);
};
using header cart button to open modal.
import React, { useContext } from "react";
import CartContext from "../Context/CartContext";
const HeaderCartBtn = () => {
const ctx = useContext(CartContext);
return (
<button className={Styles["button"]} onClick={ctx.showCart}>
<span className={Styles["icon"]}>
<CartIcon />
</span>
<span>Your Cart</span>
<span className={Styles["badge"]}>3</span>
</button>
);
};
export default HeaderCartBtn;
On clicking on Cart button on homepage, i can able to see console log. Code which i wrote to show the cart on click not working. Please suggest on this.