A Shopping Cart with React Native

Murat Sert
2 min readOct 2, 2017

--

I’ve been working on an e-commerce based React Native app and have stumbled accross the crucial question: How to implement a Shopping Cart with React Native?

Well first of all I highly recommend that you read ‘Thinking in React’ tutorial from Facebook. Although that this tutorial is aimed for ReactJS, the fundemental principles are identical and the only major difference is syntax. Implementing the Shopping Cart using Flux would be the standard recommended approach but for small scale personal projects or for junior React Developers, Flux can be a steep learning curve. Therefore I’ve decided to write my second medium article on implementing a shopping cart within React Native. This tutorial will be about the architecture and code is available from the open source below.

An image from Thinking in React, a perfect example of component segregation

First of all, lets write down the functionality we’re looking for and wrap possible components into square-brackets i.e. [Menu] for a menu component. Assume our client is a clothing brand.

“In a basic e-Commerce application, The user would browse through a list of [Products] and add the desired products into a shopping [Cart]. The Clients current product base consists of [Trousers] and [Jackets].”

Components:

-Product

— Trousers

— Jackets

-Cart

So simply we’ve identified that we’ll need four components Cart, Product, Trousers and Jackets. Please note that if you have different set of products, be sure to identify unique points and bundle them into components. Organising code into different components has many benefits such as elimination of many maintenance issues. Next, think of Product component as a base or TabBar class for quick navigation and responsible for rendering Trousers and Jacket components. So as the Product component will be the common ancestor of product related components, it is logically the most sensible place to implement an array of products within its state. So when it renders Trousers and Jacket components and if the users clicks to add a Trousers/Jacket into the Cart, we will simply pass product related data back to the Product component appending it within our Product array.

I’m pasting in the addItem and removeItem methods but a full example can be viewed from this open source repo.

--

--