Basic Shopping Cart State

Basic Shopping Cart State

Medium ReactJS State Management 30 views
Explanation Complexity

Problem Statement

Create a tiny cart that adds items and shows total quantity.

Input Format

No input.

Output Format

Render a React component.

Constraints

Store cart items in state and update immutably.

Input / Output Format

Input Format
No input.
Output Format
Render a React component.
Constraints
Store cart items in state and update immutably.

Examples

Input:
Output:
(React code)

Example Solution (Public)

ReactJS
import React, { useMemo, useState } from 'react';

const products = [
  { id: 'p1', name: 'HTML Basics', price: 0 },
  { id: 'p2', name: 'CSS Layout', price: 0 },
  { id: 'p3', name: 'React Hooks', price: 0 }
];

export default function App() {
  const [cart, setCart] = useState([]);

  function add(product) {
    setCart((prev) => {
      const existing = prev.find((x) => x.id === product.id);
      if (existing) {
        return prev.map((x) => (x.id === product.id ? { ...x, qty: x.qty + 1 } : x));
      }
      return [...prev, { ...product, qty: 1 }];
    });
  }

  const totalQty = useMemo(() => cart.reduce((sum, item) => sum + item.qty, 0), [cart]);

  return (
    <div style={{ padding: 16, display: 'grid', gap: 12, width: 520 }}>
      <strong>meetcode cart</strong>
      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
        {products.map((p) => (
          <button key={p.id} type='button' onClick={() => add(p)} style={{ padding: '10px 14px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>
            Add {p.name}
          </button>
        ))}
      </div>
      <div style={{ border: '1px solid #eee', borderRadius: 14, padding: 12 }}>
        <div style={{ fontWeight: 700 }}>Items in cart: {totalQty}</div>
        <ul style={{ margin: '10px 0 0 0', paddingLeft: 18 }}>
          {cart.map((it) => (
            <li key={it.id}>{it.name} × {it.qty}</li>
          ))}
        </ul>
      </div>
    </div>
  );
}

Official Solution Code

import React, { useMemo, useState } from 'react';

const products = [
  { id: 'p1', name: 'HTML Basics', price: 0 },
  { id: 'p2', name: 'CSS Layout', price: 0 },
  { id: 'p3', name: 'React Hooks', price: 0 }
];

export default function App() {
  const [cart, setCart] = useState([]);

  function add(product) {
    setCart((prev) => {
      const existing = prev.find((x) => x.id === product.id);
      if (existing) {
        return prev.map((x) => (x.id === product.id ? { ...x, qty: x.qty + 1 } : x));
      }
      return [...prev, { ...product, qty: 1 }];
    });
  }

  const totalQty = useMemo(() => cart.reduce((sum, item) => sum + item.qty, 0), [cart]);

  return (
    <div style={{ padding: 16, display: 'grid', gap: 12, width: 520 }}>
      <strong>meetcode cart</strong>
      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
        {products.map((p) => (
          <button key={p.id} type='button' onClick={() => add(p)} style={{ padding: '10px 14px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>
            Add {p.name}
          </button>
        ))}
      </div>
      <div style={{ border: '1px solid #eee', borderRadius: 14, padding: 12 }}>
        <div style={{ fontWeight: 700 }}>Items in cart: {totalQty}</div>
        <ul style={{ margin: '10px 0 0 0', paddingLeft: 18 }}>
          {cart.map((it) => (
            <li key={it.id}>{it.name} × {it.qty}</li>
          ))}
        </ul>
      </div>
    </div>
  );
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.