Creating a Shopping Cart

Learn how to create a shopping cart for the bookshop application.

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 ...