Integrating React Native / Expo with Firebase

Integrating React Native / Expo with Firebase cover

React Native and Expo are powerful tools for building cross-platform mobile applications. Firebase, on the other hand, provides a suite of backend services that can help you build scalable and feature-rich apps. In this guide, we'll walk through how to integrate Firebase with a React Native/Expo project and use NativeWind for styling.

Prerequisites

Before we begin, make sure you have the following installed:

  • Node.js
  • Expo CLI (npm install -g expo-cli)
  • A Firebase project (you can create one at Firebase Console)

Step 1: Create a New Expo Project

First, let's create a new Expo project:

npx create-expo-app@latest FirebaseDemo

cd FirebaseDemo

Step 2: Install Required Dependencies

Next, we need to install the necessary dependencies for Firebase and NativeWind.

Install Firebase

expo install @react-native-firebase/app

Step 3: Set Up Firebase

Initialize Firebase

Create a firebaseConfig.js file in the root of your project and add your Firebase configuration:

// firebaseConfig.js
import firebase from '@react-native-firebase/app';

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID",
};

if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
}

export { firebase };

Replace the placeholders with your actual Firebase project credentials.

Install Additional Firebase Modules (Optional)

Depending on the Firebase services you want to use, you may need to install additional modules. For example, if you want to use Firebase Authentication, you can install it like this:

expo install @react-native-firebase/auth

Step 4: Create a Simple App with Firebase and NativeWind

Now that everything is set up, let's create a simple app that uses Firebase Authentication and NativeWind for styling.

Update App.js

Replace the content of App.js with the following code:

import React, { useEffect, useState } from 'react';
import { View, Text, Button, TextInput } from 'react-native';
import { firebase } from './firebaseConfig';
import 'nativewind/global';

const App = () => {
  const [user, setUser] = useState(null);
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  useEffect(() => {
    const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
      setUser(user);
    });

    return () => unsubscribe();
  }, []);

  const handleSignUp = async () => {
    try {
      await firebase.auth().createUserWithEmailAndPassword(email, password);
    } catch (error) {
      console.error(error);
    }
  };

  const handleSignIn = async () => {
    try {
      await firebase.auth().signInWithEmailAndPassword(email, password);
    } catch (error) {
      console.error(error);
    }
  };

  const handleSignOut = async () => {
    try {
      await firebase.auth().signOut();
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <View className="flex-1 justify-center items-center bg-gray-100 p-4">
      {user ? (
        <View className="items-center">
          <Text className="text-lg font-bold">Welcome, {user.email}!</Text>
          <Button title="Sign Out" onPress={handleSignOut} />
        </View>
      ) : (
        <View className="w-full max-w-xs">
          <TextInput
            className="border border-gray-300 p-2 mb-4 rounded"
            placeholder="Email"
            value={email}
            onChangeText={setEmail}
          />
          <TextInput
            className="border border-gray-300 p-2 mb-4 rounded"
            placeholder="Password"
            value={password}
            onChangeText={setPassword}
            secureTextEntry
          />
          <Button title="Sign Up" onPress={handleSignUp} />
          <Button title="Sign In" onPress={handleSignIn} />
        </View>
      )}
    </View>
  );
};

export default App;

Explanation

  • Firebase Authentication: We use Firebase Authentication to handle user sign-up, sign-in, and sign-out.
  • NativeWind: We use NativeWind's utility classes to style our components. For example, `flex-1`, `justify-center`, `items-center`, `bg-gray-100`, etc., are all Tailwind CSS classes that are applied to our components.

Step 5: Run the App

Finally, run the app using Expo:

expo start

Scan the QR code with the Expo Go app on your phone, or run it on an emulator.

Conclusion

In this guide, we've successfully integrated Firebase with a React Native/Expo project and used NativeWind for styling. This setup provides a solid foundation for building feature-rich, scalable mobile applications with a modern styling approach. You can now extend this setup by adding more Firebase services or customizing the styling further with NativeWind.

Happy coding! 🚀

Recent Guides

Hestia Kit Premium

You have to be signed in to favorite this

Share

Hestia Kit Premium

This is Hestia Kit premium component