Create Cart Using React Context Api
Context Api
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
To know more about context follow this link: https://reactjs.org/docs/context.html
In this block we will see how we can create the cart with the help of react context api.
Firstly crate a new react app with the help of npx create-react-app react-context-cart.
Create two new folder inside src folder name as “components” and “context”
Inside the “context” create new file “product-contxt.js” and write the below code.
product-contxt.js
import React,{useState} from ‘react’;export const ProductContext = React.createContext({
products:[],
toggleCart:()=>{}
});export default props => {
const [productsList, setProductsList] = useState(
[
{
id: ‘p1’,
title: ‘Red Scarf’,
description: ‘A pretty red scarf.’,
imageUrl:”https://cdn.shopify.com/s/files/1/1058/1166/products/2_1024x1024.jpg?v=1527094021",
price:20,
isCartItem: false
},
{
id: ‘p2’,
title: ‘Blue T-Shirt’,
description: ‘A pretty blue t-shirt.’,
imageUrl:”https://cdn.pixabay.com/photo/2017/06/20/17/11/t-shirt-2423804_960_720.png”,
price:30,
isCartItem: false
},
{
id: ‘p3’,
title: ‘Black Trousers’,
description: ‘A pair of lightly black trousers.’,
imageUrl:”http://c1.peakpx.com/wallpaper/447/224/962/model-pose-woman-attractive-wallpaper-preview.jpg",
price:20,
isCartItem: false
},
{
id: ‘p4’,
title: ‘Orange Hat’,
description: ‘Street style! An orange hat.’,
imageUrl:”https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSNdCrI-1AvNIlloEGl40glUudMvCFxwH-iv2zPlEJoAWVyEWyZ”,
price:20,
isCartItem: false
}
]
);const addToCart = productId=>{
console.log(productId)
setProductsList(currentProductList=>{
const prodIndex = currentProductList.findIndex(
p => p.id === productId
);
const newStatus = !currentProductList[prodIndex].isCartItem
const updatedProduct = […productsList]
updatedProduct[prodIndex] = {
…currentProductList[prodIndex], isCartItem:newStatus
};
return updatedProduct;
});
}
return (
<ProductContext.Provider value={{products:productsList, toggleCart:addToCart}}>
{props.children}
</ProductContext.Provider>
);
};
Inside the components create two new folder “Cart” and “Product”
Inside the “Cart” create new files “Product.js”, “Product.module.css” and “ProductItem.js”
Inside the Product.js file write the following code
import React, {useContext} from ‘react’;
import {ProductContext} from ‘../../context/product-contxt’;
import ProdctItem from ‘./ProductItem’;const Products = React.memo(props =>{
const productList = useContext(ProductContext).products;
console.log(productList);
return (
<React.Fragment>
<h2 style={{textAlign:”center”}}>Product Card</h2>
{productList.map(product=>(
<ProdctItem
key={product.id}
id={product.id}
title={product.title}
decription={product.description}
imageUrl={product.imageUrl}
price = {product.price}
isCartItem={product.isCartItem}
/>
))}
</React.Fragment>
)
})export default Products
Inside the “Product.module.css” write the following code.
.Card {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
max-width: 300px;
margin: auto;
text-align: center;
font-family: arial;
float: left;
padding: 40px;
}
.Price {
color: grey;
font-size: 22px;
}
.Card button {
border: none;
outline: 0;
padding: 12px;
color: white;
background-color: #000;
text-align: center;
cursor: pointer;
width: 100%;
font-size: 18px;
}
.Card button:hover {
opacity: 0.7;
}
Inside the “ProductItem.js” write the following code
import React, {useContext} from ‘react’;
import classes from ‘./Product.module.css’;
import {ProductContext} from ‘../../context/product-contxt’;const ProductItem = props =>{
const toggleCart = useContext(ProductContext).toggleCart
const toggleFavHandler = () => {
toggleCart(props.id);
};
return(
<div className={classes.Card}>
<img src={props.imageUrl} alt=”Denim Jeans” style={{width:”100%”}} />
<h1>{props.title}</h1>
<p className={classes.Price}>${props.price}</p>
<p>{classes.decription}</p>
<p><button onClick={toggleFavHandler}>{props.isCartItem ? ‘Remove Item’ : ‘Add to Cart’}</button></p>
</div>
)
}export default ProductItem;
Edit the App.js and write the following code.
import React from ‘react’;
import logo from ‘./logo.svg’;
import ‘./App.css’;
import Product from ‘./components/Product/Product’;
import Cart from ‘./components/Cart/Cart’;const App =()=> {
return (
<React.Fragment>
<header>
<h2>React Context API</h2>
</header>
<section>
<article>
<Product />
</article>
<Cart />
</section><footer>
<p>Footer</p>
</footer>
</React.Fragment>
);
}export default App;
Open App.css and replace the css with following code
* {
box-sizing: border-box;
}
body {
font-family: Arial, Helvetica, sans-serif;
}
/* Style the header */
header {
background-color: #666;
text-align: center;
font-size: 35px;
color: white;
}/* Create two columns/boxes that floats next to each other */
nav {
float: left;
width: 25%;
height: 300px; /* only for demonstration, should be removed */
background: #ccc;
}/* Style the list inside the menu */
nav ul {
list-style-type: none;
padding: 0;
}article {
float: left;
width: 75%;
background-color: #f1f1f1;
}/* Clear floats after the columns */
section:after {
content: “”;
display: table;
clear: both;
}/* Style the footer */
footer {
background-color: #777;
padding: 10px;
text-align: center;
color: white;
}/* Responsive layout — makes the two columns/boxes stack on top of each other instead of next to each other, on small screens */
@media (max-width: 600px) {
nav, article {
width: 100%;
height: auto;
}
}
Here is my demo link: https://nny3n.csb.app/
Thank you for going through the article. If you are looking for any freelancer developer related to Html, css, React, React Native, Next.js, Node.js, GraphQl, LangChain. Please let me know. I will be glad to help you.
To tell us about your requirement please visit the contact page https://www.appingenious.com/ or please fill the form: https://docs.google.com/forms/d/1uh343ab8uwVhCpozi_etFyV67f6zVoIiMlrYKLwOgnE/prefill