Create shopping cart using Context api (useContext)

Folder - src/components :
---------------------------

Source Code Link - https://github.com/highhimanshu/shoppingcart-useContext

Cart.js:
import React, { useStateuseEffectuseContext } from 'react';
import SingleProduct from './SingleProduct';
import { C } from '../Context';

const Cart = () => {
  const { cart } = useContext(C);

  const [totalPricesetTotalPrice] = useState(0);

  console.log(cart);

  function addingPrice() {
    setTotalPrice(cart.reduce((accele=> acc + Number(ele.price), 0));
  }

  useEffect(() => {
    addingPrice();
  }, [cart]);

  return (
    <>
      <span>Total Product Added - {cart.length}</span>
      <br />
      <span>Total - $ {totalPrice} </span>
      <div className="productContainer">
        {cart.map(prod => (
          <SingleProduct p={prod} key={prod.id} />
        ))}
      </div>
    </>
  );
};

export default Cart;



Header.js:

import React, { useContext } from 'react';
import { Link } from 'react-router-dom';
import './Header.css';
import { C } from '../Context';

const Header = () => {
  const { cart } = useContext(C);

  return (
    <>
      <span className="header">Header Component </span>
      <ul className="nav">
        <li className="header1">
          <Link to="/"> Home Page</Link>
        </li>
        <li className="header2">
          <Link to="/cart"> Cart ({cart.length}</Link>
        </li>
      </ul>
    </>
  );
};

export default Header;


Header.css

.header {
  displayblock;
  text-aligncenter;
  font-weightbold;
  font-size1.5rem;
  margin10px;
}

.nav {
  displayflex;
  list-stylenone;
  justify-contentspace-around;
  align-itemscenter;
  background-colorbrown;
  padding-top20px;
  padding-bottom20px;
}

.nav > li {
  colorwhite;
  font-size17px;
  cursorpointer;
}
.nav > li :hover {
  colorrgb(224202202);
}


Home.js

import React, { useStateuseContext } from 'react';
import SingleProduct from './SingleProduct';
import faker from 'faker';
import './Home.css';
import { C } from '../Context';

faker.seed(100);

const Home = () => {
  const productArray = [...Array(20)].map(() => ({
    id: faker.datatype.uuid(),
    name: faker.commerce.productName(),
    price: faker.commerce.price(),
    image: faker.random.image()
  }));

  const [productssetProducts] = useState(productArray);

  return (
    <>
      <div className="productContainer">
        {products.map(prod => {
          return <SingleProduct p={prod} />;
        })}
      </div>
    </>
  );
};

export default Home;



Home.css

.productContainer {
  displayflex;
  padding20px;
  flex-wrapwrap;
  justify-contentspace-evenly;
}

.products {
  width25%;
  displayflex;
  flex-directioncolumn;
  padding10px;
  margin15px;
  border1px solid red;
}

.productDesc {
  displayflex;
  padding-top5px;
  justify-contentspace-between;
}

.cart-btn {
  padding5px;
  margin10px;
}



SingleProduct.js

import React, { useContext } from 'react';
import { C } from '../Context';

const SingleProduct = ({ p }) => {
  const { cartsetCart } = useContext(C);

  function addToCart() {
    setCart([...cartp]);
  }

  function removeFromCart() {
    setCart(cart.filter(c => c.id !== p.id));
  }

  return (
    <>
      <div class="products">
        <img src={p.image} alt={p.name} />
        <div className="productDesc">
          <span>{p.name}</span>
          <span>{p.price.substring(03)}</span>
        </div>
        {cart.includes(p) ? (
          <button className="cart-btn" onClick={removeFromCart}>
            Remove from cart
          </button>
        ) : (
          <button className="cart-btn" onClick={addToCart}>
            Add to Cart
          </button>
        )}
      </div>
    </>
  );
};

export default SingleProduct;



Folder - src :
-------------------------------

App.js

import React, { useState } from 'react';
import Header from './components/Header';
import Home from './components/Home';
import Cart from './components/Cart';
import { BrowserRouterRoute } from 'react-router-dom';
import './style.css';

export default function App() {
  return (
    <BrowserRouter>
      <Header />

      <Route exact path="/">
        <Home />
      </Route>
      <Route path="/cart">
        <Cart />
      </Route>
    </BrowserRouter>
  );
}



Context.js

import React, { createContextuseState } from 'react';

export const C = createContext();

const Context = ({ children }) => {
  const [cartsetCart] = useState([]);
  return <C.Provider value={cartsetCart }}>{children}</C.Provider>;
};

export default Context;


index.js

import React from 'react';
import ReactDOM from 'react-dom';
import Context from './Context';

import App from './App';

ReactDOM.render(
  <Context>
    <App />
  </Context>,
  document.getElementById('root')
);



style.css

* {
  margin0;
  padding0;
  font-familysans-serif;
}

a {
  text-decorationnone;
  colorinherit;
}










1 Comments

  1. You are one of the few who produce shopping cart using only useContext hook. I was looking for it and found it here. Most of the tubes are useContext and useReducer. Thanks for this really appreciate.

    ReplyDelete