Skip to main content

Shopping Cart React.js Project with Explanation✅ [ Simple Ecommerce Website using Reactjs ]

Hello guys in this video we will discuss shopping cart web app. 

first we need to install the basic react app using - npx create-react-app app-name

The folder structure should be containing three files  in components folder as below :


In App.js : 

import './App.css';
import Header from './components/Header';
import ProductList from './components/ProductList';
import CartList from './components/CartList';
import { useState } from 'react';

function App() {

  const [product, setProduct] = useState([
    {
      url: 'https://rukminim1.flixcart.com/image/300/300/l51d30w0/shoe/z/w/c/10-mrj1914-10-aadi-white-black-red-original-imagft9k9hydnfjp.jpeg?q=70',
      name: 'TRQ White Shoes',
      category: 'Shoes',
      seller: 'AMZ Seller Ghz',
      price: 1999
    },
    {
      url: 'https://5.imimg.com/data5/KC/PC/MY-38629861/dummy-chronograph-watch-500x500.jpg',
      name: 'LOREM Watch Black',
      category: 'Watches',
      seller: 'Watch Ltd Siyana',
      price: 2599
    },
    {
      url: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQq39iB_cO6uhZ59vubrqVuYTJQH-4Qa0hU9g&usqp=CAU',
      name: 'AMZ Laptop 8GB RAM',
      category: 'Laptops',
      seller: 'Delhi Laptops',
      price: 50000
    },
    {
      url: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQfvoDzLqrT7GwU3z7Ccp0Cl9rV0ZnU9DcmEg&usqp=CAU',
      name: 'Security Camera',
      category: 'CCTV',
      seller: 'Camron LTD',
      price: 4000
    },
    {
      url: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSG9e8Axt-h9q8EIybKfjGzbkIWJAr50_BX7Q&usqp=CAU',
      name: 'Watch Pink',
      category: 'Watches',
      seller: 'Watch Ltd',
      price: 2000
    },
    {
      url: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT9xzgtOpMxdpfgBOg3OKsEqYRkNBbuprJj4w&usqp=CAU',
      name: 'Cup red Color',
      category: 'Cup',
      seller: 'ABS Ltd',
      price: 100
    },
  ])

  const [cart, setCart] = useState([])
  const [showCart, setShowCart] = useState(false)

  const addToCart = (data) => {
    setCart([...cart, { ...data, quantity: 1 }])
  }

  const handleShow = (value) => {
    setShowCart(value)
  }

  return (
    <div>
      <Header count={cart.length}
        handleShow={handleShow} ></Header>

      {
        showCart ?
          <CartList cart={cart} ></CartList> :
          <ProductList product={product} addToCart={addToCart} ></ProductList>
      }


    </div>
  );
}

export default App;

In App.css add the following css :



.flex {
  display: flex;
  flex-wrap: wrap;
}

.shopping-card {
  justify-content: space-between;
  background-color: #61dafb;
  padding: 20px 30px;
}

.product-item {
  padding: 20px;
}

in Header.js use the following code to show cart product count :

import '../App.css';

function Header(props) {
    return (
        <div className='flex shopping-card'>
            <div onClick={() => props.handleShow(false)} >Shopping Cart App</div>
            <div onClick={() => props.handleShow(true)}> Cart
                <sup> {props.count} </sup>
            </div>
        </div>
    );
}

export default Header;

In ProductList.js file loop over the array of objects that we get as a prop from the App component

import '../App.css';

function ProductList({ product,addToCart }) {
    return (
        <div className='flex'>
            {
                product.map((productItem, productIndex) => {
                    return (
                        <div style={{ width: '33%' }}>
                            <div className='product-item'>
                                <img src={productItem.url} width="100%" />
                                <p>{productItem.name} | {productItem.category} </p>
                                <p> {productItem.seller} </p>
                                <p> Rs. {productItem.price} /-</p>
                                <button
                                    onClick={() => addToCart(productItem)}
                                >Add To Cart</button>
                            </div>
                        </div>
                    )
                })
            }
        </div>
    )
}

export default ProductList

And finally in CartList.js :

import { useEffect, useState } from 'react';
import '../App.css';

function CartList({ cart }) {

    const [CART, setCART] = useState([])

    useEffect(() => {
        setCART(cart)
    }, [cart])

    return (
        <div>
            {
                CART?.map((cartItem, cartindex) => {
                    return (
                        <div>
                            <img src={cartItem.url} width={40} />
                            <span> {cartItem.name} </span>
                            <button
                                onClick={() => {
                                    const _CART = CART.map((item, index) => {
                                        return cartindex === index ? { ...item, quantity: item.quantity > 0 ? item.quantity - 1 : 0 } : item
                                    })
                                    setCART(_CART)
                                }}
                            >-</button>
                            <span> {cartItem.quantity} </span>
                            <button
                                onClick={() => {
                                    const _CART = CART.map((item, index) => {
                                        return cartindex === index ? { ...item, quantity: item.quantity + 1 } : item
                                    })
                                    setCART(_CART)
                                }}
                            >+</button>
                            <span> Rs. {cartItem.price * cartItem.quantity} </span>
                        </div>
                    )
                })
            }

            <p> Total  <span></span>
                {
                    CART.map(item => item.price * item.quantity).reduce((total, value) => total + value, 0)
                }
            </p>
        </div >
    )
}

export default CartList

Comments

Popular posts from this blog

MERN Authentication - Login, Register, Verification Email, Forget Password, User Name & Logout on Navbar

In The React Side :  The folder structure will be : Lets start from App.js  On this file we will be adding routing , install the package react-router-dom : import './App.css' ; import React from 'react' ; import {   BrowserRouter as Router ,   Routes ,   Route ,   Link } from "react-router-dom" ; import Signup from './components/Signup' ; import Signin from './components/Signin' ; import Home from './components/Home' ; import ForgetPassword from './components/ForgetPassword' ; import NewSubmit from './components/NewSubmit' ; function App () {   return (     < div >       < Router >         < Routes >           < Route path = "/signup" element = { < Signup /> } />           < Route path = "/signin" element = { < Signin /> } />           < Route path = "/" e...

Multiple Image Uploads in React JS with NodeJs And MongoDB

In this blog we will discuss Multiple Image Uploads in React JS with NodeJs And MongoDB. For the frontend we will have an Input tag with multiple attribute to take multiple inputs in React JS example -   < input         onChange = { ( e ) => {           setImage ( e . target . files )         } }         multiple         type = "file"       /> We will the bind the onChange method with the state to save the e.target.files (FileList Array) const [ image , setImage ] = useState ([]) We will create a button to handle API submit     < button onClick = { handleSubmit } > SUBMIT </ button > So the code on App.js Becomes : import { useState } from "react" import axios from 'axios' function App () {   const [ image , setImage ] = useState ([])   const [ category , setCategory ] = useState ( 'electronics' )   c...