Make a simple Shopping Cart App using React & Redux part 2

A simple guide to learn how to use React & Redux to build a basic shopping cart app

Aya Bellazreg
3 min readDec 19, 2018

In the last part we installed everything we need for the app. Furthermore; we created a navbar composed of a Home page and a Cart page but we haven’t created them yet.

  • The Home page: will display all the provided items and will allow us to add whatever quantity of items we need.
  • The Cart page: will give us all the selected items with all the information about each product + the total.

Firstly, let’s create the Home.js:

Basic Home Page

It will look something like that:

However, we want to display our items, right? so we’re going to somehow connect the Home page with the data that we stored in the cartReducer.

To do that, we use the connect component from react-redux.

import { connect } from ‘react-redux’

Then, we need to add the mapStateToProps function(more about it later).

const mapStateToProps = (state)=>{return {    items: state.items     }}

Now we’ll connect this Home component to the data in our store and pass in our new function.

export default connect(mapStateToProps)(Home)

The mapStateToProps function:Takes the state in our cartReducer and pass it as props in our file(in this case we only need the items).

Now that we have the items data in our props, we can manipulate it however we want;

Getting items from the store(our state) and displaying them.

Finally, we get our displayed items:

The last step is to add items into the cart. For that; we need to add an onClick event to our add icon and affect it to a function that will lead eventually to add a new item to our store.

onClick={()=>{this.handleClick(item.id)}}

Now let’s create that handleClick function:

handleClick = (id)=>{this.props.addToCart(id);
}

As you can see, we called an addToCart function(taking in the id of the targetted item as a parameter) from the props. This comes from creating a mapDispatchToProps function and connecting it to our reducer.

const mapDispatchToProps= (dispatch)=>{return{   addToCart: (id)=>{dispatch(addToCart(id))}     }}

NOTE: addToCart is actually an action that the reducer will handle later on.

Adding the add to cart functionality inside the Home component.

Now let’s create that addToCart action inside our cartActions file:

export const addToCart= (id)=>{return{    type: ADD_TO_CART,     id }}

And lastly, we’ll define how we’re going to handle our addToCart action once it’s dispatched to our reducer.

Handling the addToCart action in our reducer.

Now let’s display our added items in the Cart Component

The following code will allow us to display our added items to the Cart component.

In the next part we’ll add the functionality of adding the quantity and removing an item or all the items.

Next Part

Github repository

--

--