How to Build an E-commerce App in React Native with Firebase

mrcflorian

mrcflorian

Posted on July 20, 2023

How to Build an E-commerce App in React Native with Firebase

This tutorial is intended for developers interested in building an e-commerce application using React Native and Firebase.

Prerequisites:

  • Basic understanding of JavaScript
  • Familiarity with React Native
  • Node.js and npm/yarn installed on your system
  • An active Firebase project

Getting Started

Firstly, you will need to set up a new React Native project.

If you don't have the React Native command line interface, install it globally with npm:

npm install -g react-native-cli
Enter fullscreen mode Exit fullscreen mode

Then, create a new React Native project:

react-native init ecommerceApp
Enter fullscreen mode Exit fullscreen mode

Navigate into your new project folder:

cd ecommerceApp
Enter fullscreen mode Exit fullscreen mode

I recommend using VSCode for React Native development, so get it if you don't have it yet.

Setting up Firebase

Next, install Firebase in your project:

npm install firebase
Enter fullscreen mode Exit fullscreen mode

In your Firebase console, go to "Project settings", under the gear icon, then go to "Your apps", add a new web app and copy your Firebase config object.

In your project, create a new file called Firebase.js in your root directory and paste your config object:

import firebase from 'firebase';

const firebaseConfig = {
  apiKey: "your-api-key",
  authDomain: "your-auth-domain",
  databaseURL: "your-database-url",
  projectId: "your-project-id",
  storageBucket: "your-storage-bucket",
  messagingSenderId: "your-messaging-sender-id",
  appId: "your-app-id"
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

export default firebase;
Enter fullscreen mode Exit fullscreen mode

Replace the placeholders with your Firebase details.

Creating the App Navigation

We'll use React Navigation for routing. Install it using the following command:

npm install @react-navigation/native @react-navigation/stack
Enter fullscreen mode Exit fullscreen mode

We're going to create three screens: Home, Product Details and Cart.

Let's create a new directory called screens and inside it, create three files: Home.js, ProductDetails.js, and Cart.js.

Your directory should look like this:

ecommerceApp/
  screens/
    Home.js
    ProductDetails.js
    Cart.js
  App.js
  Firebase.js
Enter fullscreen mode Exit fullscreen mode

Building the Home Screen

In Home.js, we're going to fetch the products from Firebase and display them:

import React, { useEffect, useState } from 'react';
import { View, Text, FlatList, TouchableOpacity } from 'react-native';
import firebase from '../Firebase';

const Home = ({ navigation }) => {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    const fetchProducts = async () => {
      const db = firebase.firestore();
      const data = await db.collection("products").get();
      setProducts(data.docs.map(doc => ({ ...doc.data(), id: doc.id })));
    };

    fetchProducts();
  }, []);

  return (
    <View>
      <FlatList 
        data={products}
        keyExtractor={(item) => item.id.toString()}
        renderItem={({ item }) => (
          <TouchableOpacity onPress={() => navigation.navigate('ProductDetails', { item })}>
            <Text>{item.name}</Text>
            <Text>{item.price}</Text>
          </TouchableOpacity>
        )}
      />
    </View>
  );
};

export default Home;
Enter fullscreen mode Exit fullscreen mode

Building the Product Details Screen

In ProductDetails.js, we're going to display the product details and provide an option to add the product to the cart.

import React from 'react';
import { View, Text, Button } from 'react-native';
import firebase from '../Firebase';

const ProductDetails = ({ route, navigation }) => {
  const { item } = route.params;

  const addToCart = async () => {
    const db = firebase.firestore();
    await db.collection("cart").add(item);
    navigation.navigate('Cart');
  };

  return (
    <View>
      <Text>{item.name}</Text>
      <Text>{item.description}</Text>
      <Text>{item.price}</Text>
      <Button title="Add to Cart" onPress={addToCart} />
    </View>
  );
};

export default ProductDetails;
Enter fullscreen mode Exit fullscreen mode

Building the Cart Screen

In Cart.js, we're going to fetch the products from the cart collection and display them:

import React, { useEffect, useState } from 'react';
import { View, Text, FlatList } from 'react-native';
import firebase from '../Firebase';

const Cart = () => {
  const [cart, setCart] = useState([]);

  useEffect(() => {
    const fetchCart = async () => {
      const db = firebase.firestore();
      const data = await db.collection("cart").get();
      setCart(data.docs.map(doc => ({ ...doc.data(), id: doc.id })));
    };

    fetchCart();
  }, []);

  return (
    <View>
      <FlatList 
        data={cart}
        keyExtractor={(item) => item.id.toString()}
        renderItem={({ item }) => (
          <View>
            <Text>{item.name}</Text>
            <Text>{item.price}</Text>
          </View>
        )}
      />
    </View>
  );
};

export default Cart;
Enter fullscreen mode Exit fullscreen mode

Finally, update the App.js file to include the navigation:

import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import Home from './screens/Home';
import ProductDetails from './screens/ProductDetails';
import Cart from './screens/Cart';

const Stack = createStackNavigator();

const App = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={Home} />
        <Stack.Screen name="ProductDetails" component={ProductDetails} />
        <Stack.Screen name="Cart" component={Cart} />
      </Stack.Navigator>
    </NavigationContainer>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

You now have a basic e-commerce app. You can run the app using:

react-native run-android
Enter fullscreen mode Exit fullscreen mode

or

react-native run-ios
Enter fullscreen mode Exit fullscreen mode

Remember, this is a very basic e-commerce app. For a production-ready app, you'll need to add user authentication, error handling, a checkout process, and more. You can check out this amazing fully functional React Native E-commerce App if you want to save a ton of time. Happy coding!

Find more articles at Devbrite Medium.

💖 💪 🙅 🚩
mrcflorian
mrcflorian

Posted on July 20, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related