Open In App

Create an E-commerce App using React-Native

Last Updated : 01 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

An E-commerce app using react native is an application designed to facilitate online buying and selling of goods and services. These apps aim to provide a digital platform for businesses to showcase their products or services and for consumers to browse, compare, and purchase items without the need to visit physical stores. In this article, you will learn how you can create an E-commerce App using React-Native.

create_an_e_commerce_app_using

Playground

Note: This Section is to interact with the app which you are going to build.

Prerequisites:

Step-by-Step Implementation

Step 1: Create a React Native Project

Now, create a project with the following command.

npx create-expo-app app-name --template

Note: Replace the app-name with your app name for example : react-native-demo-app

Next, you might be asked to choose a template. Select one based on your preference as shown in the image below. I am selecting the blank template because it will generate a minimal app that is as clean as an empty canvas in JavaScript.

It completes the project creation and displays a message: "Your Project is ready!" as shown in the image below.

Now go into your project folder, i.e., react-native-demo

cd app-name

Project Structure:

Step 2: Run  Application

Start the server by using the following command.

npx expo start

Then, the application will display a QR code.

  • For the Android users,
    • For the Android Emulator, press " a" as mentioned in the image below.
    • For the Physical Device, download the " Expo Go " app from the Play Store. Open the app, and you will see a button labeled " Scan QR Code. " Click that button and scan the QR code; it will automatically build the Android app on your device.
  • For iOS users, simply scan the QR code using the Camera app.
  • If you're using a web browser, it will provide a local host link that you can use as mentioned in the image below.

Step 3: Start Coding

- Approach to create an E-Commerce App:

  • We created a FlatList in the app to showcase the available products with details like name, price, and an "Add to Cart" button.
  • Implemented the ability to add products to the shopping cart using the "Add to Cart" button.
  • Shopping Cart displays the items added to the cart in a separate section using another FlatList. It also includes a "Remove" button for each item.
  • We created a "Proceed to Checkout" button that triggers the handleCheckout function. If the cart is empty, it displays a message to add products. Otherwise, displays a modal with a success message.

Let's dive into the code in detail.

- Import libraries:

Import required libraries at the top of the file.

JavaScript
// Importing useState hook from React
import { useState } from "react";
// Importing components and APIs from React Native
import {
  View,
  Text,
  FlatList,
  TouchableOpacity,
  StyleSheet,
  Button,
  Modal,
} from "react-native";

// Importing icon library from Expo
import { Ionicons } from "@expo/vector-icons";

- StyleSheet:

Create a new StyleSheet file named "Styles.js" to style components like container, heading, productItem, etc.

JavaScript
// Styles for the app components
const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: "#f5f5f5",
  },
  heading: {
    fontSize: 24,
    fontWeight: "bold",
    marginBottom: 20,
    textAlign: "center",
    color: "#333",
  },
  productItemContainer: {
    marginBottom: 10,
    borderRadius: 10,
    backgroundColor: "#fff",
    padding: 15,
    elevation: 3,
  },
  productItemName: {
    fontSize: 18,
    fontWeight: "bold",
    marginBottom: 5,
    color: "#333",
  },
  productItemPrice: {
    fontSize: 16,
    marginBottom: 10,
    color: "#666",
  },
  addButton: {
    backgroundColor: "#4caf50",
    padding: 10,
    borderRadius: 5,
    flexDirection: "row",
    justifyContent: "center",
    alignItems: "center",
  },
  addButtonText: {
    color: "white",
    marginRight: 5,
  },
  cartContainer: {
    marginTop: 20,
  },
  cartHeading: {
    fontSize: 20,
    fontWeight: "bold",
    marginBottom: 10,
    textAlign: "center",
    color: "#333",
  },
  cartItemContainer: {
    borderRadius: 10,
    backgroundColor: "#fff",
    padding: 15,
    elevation: 3,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 10,
  },
  cartItemName: {
    fontSize: 16,
    fontWeight: "bold",
    marginBottom: 5,
    color: "#333",
  },
  cartItemPrice: {
    fontSize: 14,
    color: "#666",
  },
  removeButton: {
    backgroundColor: "#e53935",
    padding: 10,
    borderRadius: 5,
    justifyContent: "center",
    alignItems: "center",
  },
  totalContainer: {
    marginTop: 10,
    alignItems: "flex-end",
  },
  totalText: {
    fontSize: 18,
    fontWeight: "bold",
    color: "#333",
  },
  checkoutButton: {
    backgroundColor: "#2196F3",
    padding: 15,
    borderRadius: 5,
    alignItems: "center",
    marginTop: 10,
  },
  checkoutButtonText: {
    color: "white",
    fontSize: 16,
    fontWeight: "bold",
  },
  modalContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "rgba(0, 0, 0, 0.5)",
  },
  modalContent: {
    backgroundColor: "#fff",
    padding: 20,
    borderRadius: 10,
    elevation: 5,
    alignItems: "center",
  },
  modalText: {
    fontSize: 18,
    marginBottom: 20,
    textAlign: "center",
  },
  emptyCartMessage: {
    fontSize: 16,
    textAlign: "center",
    marginVertical: 10,
  },
});

- Title Text:

This title explains what the app does. We use the text "E-Commerce App" to show that the app is an E-Commerce App.

JavaScript
{/* Title Text */}
<Text style={styles.heading}>E-Commerce App</Text>

- Product List:

The Below code includes,

  • Product list: List of maps of products which have keys named id, name, and price.
  • The renderProductItem function: It renders the UI of every product.
  • FlatList: It will enable the scrolling list functionality for a list of products.
JavaScript
// Initial list of products using useState hook (static data)
const [products] = useState([
    { id: "1", name: "Samsung galaxy M11", price: 70.99 },
    { id: "2", name: "MacBook pro", price: 109.99 },
    { id: "3", name: "Study Table", price: 39.99 },
]);

// Function to render each product item in the product list
const renderProductItem = ({ item }) => (
 <View style={styles.productItemContainer}>
  <Text style={styles.productItemName}>{item.name}</Text>
  <Text style={styles.productItemPrice}>
    ${item.price.toFixed(2)}
  </Text>
  <TouchableOpacity
    style={styles.addButton}
    onPress={() => addToCart(item)} // Add item to cart on press
  >
    <Text style={styles.addButtonText}>Add to Cart</Text>
    <Ionicons name="cart-outline" size={20} color="white" />
  </TouchableOpacity>
 </View>
);

{/* Product List */}
<FlatList
    data={products} // Data source
    keyExtractor={(item) => item.id} // Unique key for each item
    renderItem={renderProductItem} // Render function
/>

- addToCart function:

This function is called when the user taps on any product, and it ensures to update the list of cart products by updating the cart state variable using the setCart function.

JavaScript
// Cart state to store items added to cart
const [cart, setCart] = useState([]);

// Function to add a product to the cart
const addToCart = (product) => {
    setCart([...cart, product]); // Append product to cart array
};

- Cart Section:

This section is used to display the list of cart products, which include,

  • cart state: This is the source of cart products.
  • The renderCartItem function: it renders the UI of every cart item.
  • FlatList wrapped by View, which displays the list of cart products.
JavaScript
// Cart state to store items added to cart
const [cart, setCart] = useState([]);

// Function to render each item in the cart
const renderCartItem = ({ item }) => (
    <View style={styles.cartItemContainer}>
        <View>
            <Text style={styles.cartItemName}>{item.name}</Text>
            <Text style={styles.cartItemPrice}>
                ${item.price.toFixed(2)}
            </Text>
        </View>
        <TouchableOpacity
            style={styles.removeButton}
            onPress={() => removeFromCart(item.id)} // Remove item on press
        >
            <Ionicons name="trash-outline" size={20} color="white" />
        </TouchableOpacity>
    </View>
);


{/* Cart Section */}
<View style={styles.cartContainer}>
    <Text style={styles.cartHeading}>Shopping Cart</Text>
    
    {/* If cart is empty, show message; else show list */}
    {cart.length === 0 ? (
      <Text style={styles.emptyCartMessage}>
        Add at least one product to the cart.
      </Text>
    ) : (
      <FlatList
        data={cart}
        keyExtractor={(item) => item.id}
        renderItem={renderCartItem}
      />
)}

- Checkout Section:

This section is used to check out the cart products, which include

  • isModalVisible state: It ensures the visibility of the Modal component at the end.
  • The calculateTotal function: It calculates and returns the total amount.
  • toggleModal & handleCheckout: These functions are used to call the setModalVisible function, which updates the state of the isModalVisible state variable.
  • TouchableOpacity wrapped by View: This shows a Button with text "Proceed to Checkout", and user taps on it will call the handleCheckout function.
  • Modal Component: This component is only visible when the value of isModalVisible is true, and it will show a pop-up with text "Congratulations! Your order is placed successfully." if the user has cart items, else the text will be "Add at least one product to the cart before proceeding".
JavaScript
// Modal visibility state for checkout message
const [isModalVisible, setModalVisible] = useState(false);

// Function to calculate total price of items in the cart
const calculateTotal = () => {
    return cart.reduce((total, item) => total + item.price, 0).toFixed(2); // Sum all item prices and fix to 2 decimals
};

// Toggles modal visibility state
const toggleModal = () => {
    setModalVisible(!isModalVisible);
};

// Handles checkout logic
const handleCheckout = () => {
    // Always toggle the modal, regardless of cart state
    toggleModal();
};


{/* Display total and checkout button */}
<View style={styles.totalContainer}>
  <Text style={styles.totalText}>
    Total: ${calculateTotal()}
  </Text>
  <TouchableOpacity
    style={styles.checkoutButton}
    onPress={handleCheckout}
  >
    <Text style={styles.checkoutButtonText}>
      Proceed to Checkout
    </Text>
  </TouchableOpacity>
</View>

 {/* Checkout Modal */}
      <Modal
        animationType="slide"
        transparent={true}
        visible={isModalVisible} // Show modal if true
        onRequestClose={toggleModal} // Required for Android
      >
        <View style={styles.modalContainer}>
          <View style={styles.modalContent}>
            {/* Show different message based on cart state */}
            <Text style={styles.modalText}>
              {cart.length === 0
                ? "Add at least one product to the cart before proceeding."
                : "Congratulations! Your order is placed successfully."}
            </Text>
            {/* Close button */}
            <Button title="Close" onPress={toggleModal} />
          </View>
        </View>
      </Modal>

Now, wrap all design code with a View component, return it from the App component, and place all methods and useStates within the App component. Ensure to export the App.

Complete Source Code

App.js:

App.js
// Importing useState hook from React
import { useState } from "react";
// Importing components and APIs from React Native
import {
  View,
  Text,
  FlatList,
  TouchableOpacity,
  StyleSheet,
  Button,
  Modal,
} from "react-native";

// Importing icon library from Expo
import { Ionicons } from "@expo/vector-icons";

// Main functional component for the e-commerce app
const ECommerceApp = () => {
  // Initial list of products using useState hook (static data)
  const [products] = useState([
    { id: "1", name: "Samsung galaxy M11", price: 70.99 },
    { id: "2", name: "MacBook pro", price: 109.99 },
    { id: "3", name: "Study Table", price: 39.99 },
  ]);

  // Cart state to store items added to cart
  const [cart, setCart] = useState([]);

  // Modal visibility state for checkout message
  const [isModalVisible, setModalVisible] = useState(false);

  // Function to add a product to the cart
  const addToCart = (product) => {
    setCart([...cart, product]); // Append product to cart array
  };

  // Function to remove a product from the cart by ID
  const removeFromCart = (productId) => {
    const updatedCart = cart.filter((item) => item.id !== productId); // Remove item
    setCart(updatedCart); // Update cart
  };

  // Function to calculate total price of items in the cart
  const calculateTotal = () => {
    return cart.reduce((total, item) => total + item.price, 0).toFixed(2); // Sum all item prices and fix to 2 decimals
  };

  // Function to render each product item in the product list
  const renderProductItem = ({ item }) => (
    <View style={styles.productItemContainer}>
      <Text style={styles.productItemName}>{item.name}</Text>
      <Text style={styles.productItemPrice}>
        ${item.price.toFixed(2)}
      </Text>
      <TouchableOpacity
        style={styles.addButton}
        onPress={() => addToCart(item)} // Add item to cart on press
      >
        <Text style={styles.addButtonText}>Add to Cart</Text>
        <Ionicons name="cart-outline" size={20} color="white" />
      </TouchableOpacity>
    </View>
  );

  // Function to render each item in the cart
  const renderCartItem = ({ item }) => (
    <View style={styles.cartItemContainer}>
      <View>
        <Text style={styles.cartItemName}>{item.name}</Text>
        <Text style={styles.cartItemPrice}>
          ${item.price.toFixed(2)}
        </Text>
      </View>
      <TouchableOpacity
        style={styles.removeButton}
        onPress={() => removeFromCart(item.id)} // Remove item on press
      >
        <Ionicons name="trash-outline" size={20} color="white" />
      </TouchableOpacity>
    </View>
  );

  // Toggles modal visibility state
  const toggleModal = () => {
    setModalVisible(!isModalVisible);
  };

  // Handles checkout logic
  const handleCheckout = () => {
    // Always toggle the modal, regardless of cart state
    toggleModal();
  };

  // Main UI layout returned by the component
  return (
    <View style={styles.container}>
      {/* Title Heading */}
      <Text style={styles.heading}>E-Commerce App</Text>

      {/* Product List */}
      <FlatList
        data={products} // Data source
        keyExtractor={(item) => item.id} // Unique key for each item
        renderItem={renderProductItem} // Render function
      />

      {/* Cart Section */}
      <View style={styles.cartContainer}>
        <Text style={styles.cartHeading}>Shopping Cart</Text>

        {/* If cart is empty, show message; else show list */}
        {cart.length === 0 ? (
          <Text style={styles.emptyCartMessage}>
            Add at least one product to the cart.
          </Text>
        ) : (
          <FlatList
            data={cart}
            keyExtractor={(item) => item.id}
            renderItem={renderCartItem}
          />
        )}

        {/* Display total and checkout button */}
        <View style={styles.totalContainer}>
          <Text style={styles.totalText}>
            Total: ${calculateTotal()}
          </Text>
          <TouchableOpacity
            style={styles.checkoutButton}
            onPress={handleCheckout}
          >
            <Text style={styles.checkoutButtonText}>
              Proceed to Checkout
            </Text>
          </TouchableOpacity>
        </View>
      </View>

      {/* Checkout Modal */}
      <Modal
        animationType="slide"
        transparent={true}
        visible={isModalVisible} // Show modal if true
        onRequestClose={toggleModal} // Required for Android
      >
        <View style={styles.modalContainer}>
          <View style={styles.modalContent}>
            {/* Show different message based on cart state */}
            <Text style={styles.modalText}>
              {cart.length === 0
                ? "Add at least one product to the cart before proceeding."
                : "Congratulations! Your order is placed successfully."}
            </Text>
            {/* Close button */}
            <Button title="Close" onPress={toggleModal} />
          </View>
        </View>
      </Modal>
    </View>
  );
};

// Styles for the app components
const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: "#f5f5f5",
  },
  heading: {
    fontSize: 24,
    fontWeight: "bold",
    marginBottom: 20,
    textAlign: "center",
    color: "#333",
  },
  productItemContainer: {
    marginBottom: 10,
    borderRadius: 10,
    backgroundColor: "#fff",
    padding: 15,
    elevation: 3,
  },
  productItemName: {
    fontSize: 18,
    fontWeight: "bold",
    marginBottom: 5,
    color: "#333",
  },
  productItemPrice: {
    fontSize: 16,
    marginBottom: 10,
    color: "#666",
  },
  addButton: {
    backgroundColor: "#4caf50",
    padding: 10,
    borderRadius: 5,
    flexDirection: "row",
    justifyContent: "center",
    alignItems: "center",
  },
  addButtonText: {
    color: "white",
    marginRight: 5,
  },
  cartContainer: {
    marginTop: 20,
  },
  cartHeading: {
    fontSize: 20,
    fontWeight: "bold",
    marginBottom: 10,
    textAlign: "center",
    color: "#333",
  },
  cartItemContainer: {
    borderRadius: 10,
    backgroundColor: "#fff",
    padding: 15,
    elevation: 3,
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    marginBottom: 10,
  },
  cartItemName: {
    fontSize: 16,
    fontWeight: "bold",
    marginBottom: 5,
    color: "#333",
  },
  cartItemPrice: {
    fontSize: 14,
    color: "#666",
  },
  removeButton: {
    backgroundColor: "#e53935",
    padding: 10,
    borderRadius: 5,
    justifyContent: "center",
    alignItems: "center",
  },
  totalContainer: {
    marginTop: 10,
    alignItems: "flex-end",
  },
  totalText: {
    fontSize: 18,
    fontWeight: "bold",
    color: "#333",
  },
  checkoutButton: {
    backgroundColor: "#2196F3",
    padding: 15,
    borderRadius: 5,
    alignItems: "center",
    marginTop: 10,
  },
  checkoutButtonText: {
    color: "white",
    fontSize: 16,
    fontWeight: "bold",
  },
  modalContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "rgba(0, 0, 0, 0.5)",
  },
  modalContent: {
    backgroundColor: "#fff",
    padding: 20,
    borderRadius: 10,
    elevation: 5,
    alignItems: "center",
  },
  modalText: {
    fontSize: 18,
    marginBottom: 20,
    textAlign: "center",
  },
  emptyCartMessage: {
    fontSize: 16,
    textAlign: "center",
    marginVertical: 10,
  },
});

// Export the component for use in other files
export default ECommerceApp;

Output:


Next Article

Similar Reads