skip to Main Content

I am in the process of creating a shopping page which contains an array of items, I have also implemented functions such as "addToCart", "removeFromCart", "increaseQuantity" and "decreaseQuantity". However, when I pass these values as a prop to the cart page, I encounter an issue where after selecting the cart title from the navbar the page fails to render properly "It shows a blank screen". Despite having checked my methods using console logs, I am still unable to determine the root cause of the issue!

Here’s the react.js code:

App.js:

import { BrowserRouter as Router, Routes, Route, } from 'react-router-dom';
import Shop from './Components/Pages/A-Shop/Shop';
import Cart from './Components/Pages/Cart'
import NavBar from './Components/NavBar';
function App() {

  return (

    <div className='App'>

      <Router>
        <NavBar />
        <Routes>
          <
          <Route path='/Shop' element={<Shop />} />
          <Route path='/cart' element={<Cart />} />

          <Route path='*' element={<ErrorPage />} />

        </Routes>

      </Router>
    </div>

  );
}

export default App;

NavBar.js:

import { NavLink } from "react-router-dom";

function NavBar() {
    return (
        <nav>
            <NavLink to="/" id="title"> Clean energy for business</NavLink>

            <div>
                <ul id='navbar'>
                    <NavItem to='/' label='Home' />
                    <NavItem to='/Shop' label='Shop' />
                    <NavItem to='/Profile' label='Profile' />
                    <NavItem to='/Cart' label='Cart' />

                </ul>

            </div>
        </nav >
    );
}

function NavItem({ to, label }) {
    return (
        <li>
            <NavLink to={to} activeClassName='active'>
                {label}
            </NavLink>
        </li>
    );
}

export default NavBar;

Shop.js:

import { useState } from 'react';
import Cart from '../Cart';


function Shop() {
    const [cartItems, setCartItems] = useState([]);

    const items = [
        { id: 1, name: 'T-shirt', price: 25, image: 'images/Shop/6.png' },
        { id: 2, name: 'Patch', price: 10, image: 'images/Shop/4.PNG' },
        { id: 3, name: 'Cap', price: 20, image: 'images/Shop/3.png' },
        { id: 4, name: 'Bandana', price: 15, image: 'images/Shop/2.png' },
        { id: 5, name: 'Bag', price: 20, image: 'images/Shop/1.png' },
        { id: 6, name: 'Socks', price: 20, image: 'images/Shop/5.png' }
    ];

    const addToCart = (item) => {
        const index = cartItems.findIndex((cartItem) => cartItem.id === item.id);
        if (index === -1) {
            setCartItems([...cartItems, { ...item, quantity: 1 }]);
        } else {
            const newCartItems = [...cartItems];
            newCartItems[index].quantity++;
            setCartItems(newCartItems);
        }
    };

    const removeFromCart = (item) => {
        const newCartItems = [...cartItems];
        const index = newCartItems.findIndex((cartItem) => cartItem.id === item.id);
        newCartItems.splice(index, 1);
        setCartItems(newCartItems);
    };

    const increaseQuantity = (item) => {
        const newCartItems = [...cartItems];
        const index = newCartItems.findIndex((cartItem) => cartItem.id === item.id);
        newCartItems[index].quantity++;
        setCartItems(newCartItems);
    };

    const decreaseQuantity = (item) => {
        const newCartItems = [...cartItems];
        const index = newCartItems.findIndex((cartItem) => cartItem.id === item.id);
        if (newCartItems[index].quantity > 1) {
            newCartItems[index].quantity--;
            setCartItems(newCartItems);
        }
    };

    return (
        <div className='Shop'>
            <h1 className='shop-title'>Shopping Page</h1>
            <div className="item-list">
                {items.map((item) => (
                    <div key={item.id} className="item">
                        <img className='shop-image' src={item.image} alt={item.name} />
                        <h2>{item.name}</h2>
                        <p>£{item.price}</p>
                        <button className='shop-button' onClick={() => addToCart(item)}>Add to Cart</button>
                    </div>
                ))}
            </div>
            <Cart
                cartItems={cartItems}
                removeFromCart={removeFromCart}
                increaseQuantity={increaseQuantity}
                decreaseQuantity={decreaseQuantity}
            />
        </div>
    );
}

export default Shop;

Cart.js:



const Cart = (props) => {
    const cartItems = props.cartItems;
    const removeFromCart = props.removeFromCart;
    const increaseQuantity = props.increaseQuantity;
    const decreaseQuantity = props.decreaseQuantity;
    return (
        <div className='Cart'>
            <h1 className='cart-title'>Cart Page</h1>
            <div className="cart-items">
                {cartItems.map((item) => (
                    <div key={item.id} className="cart-item">
                        <img className='cart-image' style={{ width: "100px", height: "100px" }} src={item.image} alt={item.name} />
                        <h2>{item.name}</h2>
                        <p>£{item.price}</p>
                        <p>Quantity: {item.quantity}</p>
                        <button className='cart---button' onClick={() => increaseQuantity(item)}>+</button>
                        <button className='cart---button' onClick={() => decreaseQuantity(item)}>-</button>
                        <button className='cart-remove-button' onClick={() => removeFromCart(item)}>Remove</button>
                    </div>
                ))}
            </div>

        </div>
    );
};

export default Cart;

I have tried console log the code, and it shows that the code is functional, but still I don’t understand why I can’t render the cart page.

2

Answers


  1. You can Add this condition on Shop.js:

    {cartItems.length > 0 &&
    <Cart
                    cartItems={cartItems}
                    removeFromCart={removeFromCart}
                    increaseQuantity={increaseQuantity}
                    decreaseQuantity={decreaseQuantity}
                />
    }
    
    

    Cart.js

    const Cart = (props) => {
        const cartItems = props.cartItems;
        const removeFromCart = props.removeFromCart;
        const increaseQuantity = props.increaseQuantity;
        const decreaseQuantity = props.decreaseQuantity;
        return (
            <div className='Cart'>
                <h1 className='cart-title'>Cart Page</h1>
                <div className="cart-items">
                    {cartItems.length > 0 && cartItems.map((item) => (
                        <div key={item.id} className="cart-item">
                            <img className='cart-image' style={{ width: "100px", height: "100px" }} src={item.image} alt={item.name} />
                            <h2>{item.name}</h2>
                            <p>£{item.price}</p>
                            <p>Quantity: {item.quantity}</p>
                            <button className='cart---button' onClick={() => increaseQuantity(item)}>+</button>
                            <button className='cart---button' onClick={() => decreaseQuantity(item)}>-</button>
                            <button className='cart-remove-button' onClick={() => removeFromCart(item)}>Remove</button>
                        </div>
                    ))}
                </div>
    
            </div>
        );
    };
    
    export default Cart;
    
    Login or Signup to reply.
  2. I just ran your code and have the following findings. Your cart component is working fine when you are rendering it from inside Shop component. Because you are passing the necessary props to it. Cart Components with props

    But when you are trying to render the Cart component independently from routes, you are not passing the props to the components. That’s why it is giving error when you are trying to load that route (/cart). Cart component issue

    Solution – You need to use global store like redux or context to make all the selected items available on the separate route. and make the cart component independent of props.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search