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 = "/" element = { < Home /> } />           < Route

API Call In React JS using Axios [ React Form Submit To API ]

 Step 1 : npm i axios.  Step 2 : Create form with email and password.  Step 3 : create state to store email and password.  Step 4 : Store the value in state using onChange method.   Step 5 : Call the Api with data stored in state.   Step 6 : Handle Error and Success.   App.js Code below : import { useState } from "react" ; import './App.css' ; import axios from "axios" ; function App () {   const [ email , setEmail ] = useState ( '' )   const [ password , setPassword ] = useState ( '' )   console . log ({ email , password })   const handleEmail = ( e ) => {     setEmail ( e . target . value )   }   const handlePassword = ( e ) => {     setPassword ( e . target . value )   }   const handleApi = () => {     console . log ({ email , password })     axios . post ( 'https://reqres.in/api/login' , {       email : email ,       password : password     }). then ( result => {       console . log ( result .