Create a Shopping Cart in React with Redux Toolkit Part 2

2 years ago admin Reactjs

In the second part of this tutorial, we will add the main components, we will display the products on the homepage, we will also add, update, and remove products from the cart.


Create the ProductListItem component

Inside components, we add a new file ProductListItem.js.

                                                    
                                                                                                                
import React from 'react';
import { useDispatch } from 'react-redux';
import { addToCart } from './features/cartSlice';

export default function ProductListItem({product}) {
    const dispatch = useDispatch();

    return (
        <div className="col-md-4 mb-2">
            <div className="card" style={{width: '18rem'}}>
                <img src={product.image} className="card-img-top" alt="..." />
                <div className="card-body">
                    <h5 className="card-title">{product.name}</h5>
                    <p className="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
                    <button 
                        onClick={() => {
                            let item = null;
                            item = {...product, quantity: 1};
                            dispatch(addToCart(item));
                        }} 
                        className="btn btn-primary">
                        <i className="bi bi-cart-check"></i> add to cart
                    </button>
                </div>
            </div>
        </div>
    )
}


Create the ProductList component

Inside components, we add a new file ProductList.js.

                                                        
                                                                                                                        
import React from 'react';
import { useSelector } from 'react-redux';
import ProductListItem from './ProductListItem';


export default function ProductList() {
    const { products } = useSelector(state => state.product);

    return (
        <div className='row my-4'>
            {
                products.map(product => <ProductListItem key={product.id}
                    product={product} />)
            }
        </div>
    )
}


Create the Home and the Header component

Inside components, we add two new files Header.js and Home.js.

                                                        
                                                                                                                        
//Header.js
import React from 'react';
import { useSelector } from 'react-redux';
import { Link } from 'react-router-dom';


export default function Header() {
    const { cartItems } = useSelector(state => state.cart);

    return (
        <nav className="navbar navbar-expand-lg navbar-dark bg-dark">
            <div className="container-fluid">
                <Link className="navbar-brand" to="/">React Shopping Cart</Link>
                    <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                <span className="navbar-toggler-icon"></span>
                </button>
                <div className="collapse navbar-collapse" id="navbarSupportedContent">
                    <ul className="navbar-nav me-auto mb-2 mb-lg-0">
                        <li className="nav-item">
                            <Link className="nav-link" aria-current="page" to="/">Home</Link>
                        </li>
                        <li className="nav-item">
                            <Link className="nav-link" to="/cart"><i className="bi bi-cart-check"></i> ({cartItems.length})</Link>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
    )
}

//Home.js
import React from 'react';
import ProductList from "./ProductList"; 

export default function Home() {
    return (
        <ProductList />
    )
}


Create the Cart component

Inside components, we add a new file Cart.js.

                                                        
                                                                                                                        
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { decrementQ, incrementQ, removeFromCart } from './features/cartSlice';

export default function Cart() {
    const { cartItems } = useSelector(state => state.cart);
    const dispatch = useDispatch();
    
    return (
        <div className='row my-4'>
            <div className="col-md-12">
                <div className="card">
                    <div className="card-body">
                        <table className="table">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Image</th>
                                    <th>Name</th>
                                    <th>Quantity</th>
                                    <th>Price</th>
                                    <th>Subtotal</th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                                {
                                    cartItems.map(item => (
                                        <tr key={item.id}>
                                            <td>{item.id}</td>
                                            <td>
                                                <img src={item.image} 
                                                className='fluid rounded'
                                                width={60}
                                                height={60}    
                                                alt={item.name} />
                                            </td>
                                            <td>
                                                {item.name}
                                            </td>
                                            <td>
                                                <i 
                                                    onClick={() => dispatch(incrementQ(item))}
                                                    style={{cursor: 'pointer'}}
                                                    className="bi bi-caret-up"></i>
                                                <span className="mx-2">
                                                    {item.quantity}
                                                </span>
                                                <i 
                                                    onClick={() => dispatch(decrementQ(item))}
                                                    style={{cursor: 'pointer'}}
                                                    className="bi bi-caret-down"></i>
                                            </td>
                                            <td>
                                                ${item.price}
                                            </td>
                                            <td>
                                                ${item.price * item.quantity} 
                                            </td>
                                            <td>
                                                <i 
                                                    onClick={() => dispatch(removeFromCart(item))}
                                                    style={{cursor: 'pointer'}}
                                                    className="bi bi-cart-x text-danger"></i>
                                            </td>
                                        </tr>
                                    ))
                                }
                                <tr>
                                    <th colSpan={3} className='text-center'>
                                        Total
                                    </th>
                                    <td colSpan={3} className='text-center'>
                                        <span className="badge bg-danger rounded-pill">
                                            ${
                                                cartItems.reduce((acc,item) => acc += item.price * item.quantity,0)
                                            }
                                        </span>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    )
}


Update App component

Inside the root folder, we update the file App.js, you can download the source code from here.

                                                        
                                                                                                                        
import Header from "./components/Header";
import { Routes, Route } from "react-router-dom";
import Cart from "./components/Cart";
import Home from "./components/Home";

function App() {
  return (
    <div className="container">
      <Header />
      <Routes>
        <Route path="/" exact element={<Home />} />
        <Route path="/cart" exact element={<Cart />} />
      </Routes>
    </div>
  );
}

export default App;

Related Tuorials

Build a Shopping Cart Using React js Laravel 11 & Stripe Payment Gateway Part 5

In the last part of this tutorial, we will display the cart items, add the ability to increment/decr...


Build a Shopping Cart Using React js Laravel 11 & Stripe Payment Gateway Part 4

In the fourth part of this tutorial, we will fetch and display all the products on the home page, an...


Build a Shopping Cart Using React js Laravel 11 & Stripe Payment Gateway Part 3

In the third part of this tutorial, we will start coding the front end, first, we will install the p...


Build a Shopping Cart Using React js Laravel 11 & Stripe Payment Gateway Part 2

In the second part of this tutorial, we will create the product and payment controllers, and later w...


Build a Shopping Cart Using React js Laravel 11 & Stripe Payment Gateway Part 1

In this tutorial, we will create a shopping cart using React js Laravel 11 and Stripe payment gatewa...


How to Use Rich Text Editor in React js

In this lesson, we will see how to use rich text editor in React JS, let's assume that we have a com...


How to Download a File from the Server Using Laravel and React js

In this tutorial, we will see how to download a file from the server using Laravel and React js, let...


How to Add a Class on Hover in React js

In this lesson, we will see how to add a class on hover in React js, let's assume that we have a boo...


Drag and Drop Image and File Upload Using React and Laravel

In this tutorial, we will see how to upload files using drag and drop in React js and Laravel, first...


API Authentication Using Laravel Sanctum and React js Part 3

In the third part of this tutorial, we will register and log in the user, get the access token, and...