How to implement a shopping cart with React and Redux
When you build a eCommerce website, you must implement a shopping cart module. I’m the owner of the open source project react-ecommerce ( Frontend), react-backoffice (Admin Frontend) and node-ecommerce(Backend). I use this project to build a lot of eCommerce website. Today, I’m going to introduce how I implement the shopping cart.
I assume the reader is using mac or linux with node installed, if you use windows you may need to have git bash and node installed, so that you can run npm install.
Create the project
Firstly we need to create a new react project by issue the command:
cd ~/
npx create-react-app my-cart
Install the dependencies
In this small app we add the react-router-dom to handle routes, add react-redux to help use do app state management, and we use material-ui as our ui framework:
cd ~/my-cart
npm i react-router-dom --save
npm i react-redux --save
npm i @material-ui/core --save
Add Pages
Now we create a /pages folder and add two pages, a home page which display the shopping cart result, and a product list page to select the product.
We add a HomePage.js with empty orders, and a link to navigate to the product list:
Then we create a ProductListPage.js with a fake product list, and there is an ‘Add to Cart’ button beside each product:
Setup the routes and route to pages
Now we need to create the routes so that we can navigate pages.
Firstly add a file called Route.js in /src folder:
Then we need to add this Route.js to App.js, we replace the default content in App.js with following:
Run Our App First Time
Now we can try our app by open a terminal and issue following commands:
cd ~/my-cart
npm start
We should be able to open a webpage in browser from http://localhost:3000/ and navigate pages!
Add Redux
Next we arrive to the key step, we need the setup the redux, and then put all our logic into redux, this is typically how modern web app handle the state management. Because the items and quantity change of the cart is the state mutation of our app.
We create a redux folder and then create a cart.actions.js
And create a cart.reducers.js
Then we create a store.js file in our /redux folder to collect the reducers.
We hookup our store in index.js, our index.js becomes:
Connect Redux to our pages
To connect ProductListPage.js, we add our logic in handleAddToCart function, and add mapStateToProps and our action shorthands, here is the new ProductListPage.js:
And we load redux cart in our HomePage.js and render the result:
All Set and Have fun !
Now stop our previous service by hit ‘Ctrl + C’ in our terminal, then restart our service:
npm start
Now we have a basic front-end Shopping Cart!
What’s the next?
Next we will introduce:
- How to create unit test for this shopping cart
- How to make this shopping cart to support Combo product
- How to create a nodejs mongodb backend with real data
- How to create transaction records and hook up finance