CodeBlanks Logo Icon CodeBlanks

Add product UI

Write a panel that lists products and adds them to the cart.

Add-to-cart UI

The final lesson writes the ProductCard and CartSummary components. The product card dispatches ADD; the summary reads total from state.

ProductCard: gets dispatch with const dispatch = useContext(CartDispatchContext);. On button click, dispatch({ '{ type: "ADD", payload: product }' }).

CartSummary: reads state with const state = useContext(CartStateContext);. Shows state.total and state.items.length. This is where the three lessons merge.

Cart summary

CartSummary reads state with useContext(CartStateContext). state.items.length gives item count, state.total gives total. It prints both.

On every state change (ADD, REMOVE, CLEAR), CartSummary re-renders automatically. ProductCard using CartDispatchContext isn't affected by state changes.

This is where the power of two contexts shows: components that only read or only write don't render needlessly. This gives a smooth experience in big cart apps.

Practice Write ProductCard

Complete the skeleton. Write a ProductCard component. Take ({ '{ product }' }). Get dispatch with const dispatch = useContext(CartDispatchContext);. Return <div><h3>{ '{ product.name }' }</h3><p>{ '{ product.price }' } TL</p><button onClick={ '{ () => dispatch({ '{ type: "ADD", payload: product }' }) }' }>Add</button></div>. Export it.

Starter code

App.jsx
import { useContext } from "react";

// Write the ProductCard component here

Sample solution

App.jsx
import { useContext } from "react";

function ProductCard({ product }) {
  const dispatch = useContext(CartDispatchContext);
  return (
    <div>
      <h3>{product.name}</h3>
      <p>{product.price} TL</p>
      <button onClick={() => dispatch({ type: "ADD", payload: product })}>Add</button>
    </div>
  );
}

export default ProductCard;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which context does ProductCard use?

  • CartDispatchContext Correct answer
  • CartStateContext
  • ThemeContext
  • UserContext

Explanation: ProductCard uses CartDispatchContext.

2 ADD action

Question
To add a product, dispatch({ type: "ADD", payload: product }); product goes into ____.
Answer
To add a product, dispatch({ type: "ADD", payload: product }); product goes into payload.

Explanation: product goes into payload.

3 Match the add-to-cart flow

Term Meaning
ProductCard ADD
dispatch cartReducer
CartSummary state.total
CartProvider wraps

All lessons in Intermediate