Search⌘ K
AI Features

Creating a Shopping Cart

Explore how to build a shopping cart component for a Meteor.js full-stack online bookshop using React context. Understand managing global cart state, adding and removing items, adjusting quantities, and calculating totals including shipping fees. This lesson helps you implement a functional cart accessible across components, enhancing your full-stack application skills.

A shopping cart is used to display the list of items selected by a user and the price associated with each item. The cart will be placed in a global state so that it can be accessed anywhere in the component tree. One way to make the state global in React is by using React context.

Shopping context

Open the imports/context/ShoppingContext.jsx file. We’ll create a global state using React context. On line 3, we define a ShoppingContext. To use the ShoppingContext, we define a function that we’ll call ShoppingProvider.

The ShoppingProvider function uses a React state called cart and a function called setCart that changes the state. On line 7, we save an object with the {cart, setCart} keys to a variable named value.

The function returns a ShoppingContext.Provider component with the value prop passed to it on line 9. The ShoppngContext.Provider component wraps and returns the children prop that’s passed to the ...