Building a Reusable Firebase Facebook Login Component
Tags: frontend, react, programming, firebase
Published: 2019-07-02 16:52:29

---
title: Building a Reusable Firebase Facebook Login Component
published: true
tags: frontend,react,programming,firebase
canonical_url: https://blog.bitsrc.io/building-a-reusable-firebase-facebook-login-component-eaa098f58f17
---

#### Learn how to build a reusable and shareable Firebase Facebook login component

![](https://cdn-images-1.medium.com/max/1024/1*ED7mmgYYeUZkz8iIz2g3SQ.png)

In this tutorial, we are following the first chapter of clone [Firebaseweb-UI demo](https://fir-ui-demo-84a6c.firebaseapp.com/) and use codes from it as well. Here, we are going to learn how to create a reusable and shareable Facebook login component with React and [Bit](https://bit.dev). First, we will prepare a facebook login component using firebase integration and authentication in a React project. Then, we are will push the code to Bit. We will also learn to import modules from packages installed using the Node Package Manager(NPM). We have broken down this tutorial into various sub-headings for you to grasp the concept and work accordingly.

### What you’ll learn …?

- How to create new React app.
- How to install and using firebase in React.
- How to use Firebase Authentication.
- How to create and set up a Facebook app.
- How to install and use [Bit](https://bit.dev).
- How to pass props in React.

### Problem

[Firebaseweb-UI](https://fir-ui-demo-84a6c.firebaseapp.com/) demo built using vanillaJS is not split up into component which makes it hard for maintenance purpose. Since the components are not used, the codes may be re-written in most parts creating a heavy form of project.

### Requirements

Here’s a complete list of plugins, packages, and services you’re going to need in order to gain something from this tutorial:

- Nodejs v8.x.x or higher installed along with NPM/yarn.
- Firebase, Bit and Facebook developer account.
- Already installed React project.
- Firebase and Bit package.

### First Step

Before working on the Facebook login component, we are going to complete every configuration required while using _App.js_.

Firstly, try to grab CSS from Firebaseweb-UI demo and paste from

**firebase-ui.css** ->  **App.css**

Here, we need to include firebase CSS to _App.js_.

Then include some styles to _Index.css,_

**style.css** -> **Index.css**

which we need to include in the _index.js_ file.

Then, we need to grab the button code from firebaseweb-ui and then add it to our _App.js_ code as follows:

{% gist https://gist.github.com/krissnawat/ea369f64e14e6d82ce0a25cf358d3a08 %}

Now, in the browser, we can see the facebook login component button. The screenshot of the result from the above code snippet is shown below:

![](https://cdn-images-1.medium.com/max/310/1*cKmz3FgRwpR0H-bkUbI-Mg.png)

### Second Step: create and setup Facebook App and Firebase

In this step, we are integrating facebook login with firebase. You will need to create a facebook app from your facebook developer account which will include APP\_ID and APP\_SECRET key. Then, open your facebook developer account and copy APP\_ID and APP\_SECRET. After that, we need to paste it on firebase console as shown in the screenshot below:

![](https://cdn-images-1.medium.com/max/984/1*upkycCFmYxpQEOrMr-NqnQ.png)

Then, we need to open the firebase console and paste APP\_ID and APP\_SECRET key on authentication sign-in method tab as shown in the screenshot below:

![](https://cdn-images-1.medium.com/max/976/1*2iCOmT5gBsPr6GT7haXLBw.png)

After that, you will see a redirect URI at the bottom as shown in the screenshot above. We need to copy that redirect URI. Then, return to the Facebook developer console. In the developer console, we need to go to Facebook login setting and scroll to Valid OAuth Redirect and paste the URI there as shown in the screenshot below:

![](https://cdn-images-1.medium.com/max/1024/1*2vmtptByOn0oF0qcczIzUQ.png)

Then, just save the configuration.

In the next step, we need to create a Firebase app. Here, we need to get firebase configuration and paste it on our App.js file. The configuration for the firebase is given below:

```
const firebaseConfig = {
  apiKey: "xxxxxxxxxxx",
  authDomain: "xxxxxxxxxxx.firebaseapp.com",
  databaseURL: "https://xxxxxxxxxxx.firebaseio.com",
  projectId: "xxxxxxxxxxx",
  storageBucket: "xxxxxxxxxxx.appspot.com",
  messagingSenderId: "xxxxxxxxxxx",
  appId: "1:14017xxxxxxxxxxx382be09e",
};
```

Now, we need to import _firebase_ from firebase/app package and firebase/auth package which is necessary to configure other modules and firebase and its authentication configuration.

```
import firebase from "firebase/app";
import "firebase/auth";
```

Now, we need to create a constructor that handles initialize firebase as shown in the code snippet below:

```
constructor(props) {
    super(props);

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

Then, we need to create a new function to trigger Firebase Authentication with the Facebook code shown below which you can find on Firebase doc.

```
handleLogin() {
    var provider = new firebase.auth.FacebookAuthProvider();
    firebase
      .auth()
      .signInWithPopup(provider)
      .then(function(result) {
        // This gives you a Facebook Access Token. You can use it to access the Facebook API.
        var token = result.credential.accessToken;
        // The signed-in user info.
        var user = result.user;
        console.log(user);
        // ...
      })
      .catch(function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // The email of the user's account used.
        var email = error.email;
        // The firebase.auth.AuthCredential type that was used.
        var credential = error.credential;
        // ...
      });
  }
```

### Third Step: let’s make it work

In this step, we are going to make everything work and configured properly. First, add ahandleLogin button to handle to trigger a _handleLogin_ function as shown in the code snippet below:

```
<button onClick={this.handleLogin} ... />
```

Now, test the login operation which can be seen in the simulation below:

![](https://cdn-images-1.medium.com/max/1024/1*yAritO6H672zTbrTfHa2HA.gif)

Hence, you can see that it works like a charm.

Now, we need to make it better using Bit.

### Make it Reusable and Sharable with Bit

[Share reusable code components as a team · Bit](https://bit.dev)

To make our code reusable and shareable, we’ll do some restructuring and move all our code to ‘components’ (this is not mandatory but a better practice, when using [Bit](https://bit.dev)). Then, we’ll export it (with all its dependencies), to a component collection on [Bit’s cloud](https://bit.dev/components), to be shared with others and easily reused.

Now, we structure our component as shown in the project folder structure below:

![](https://cdn-images-1.medium.com/max/273/1*bVZk7yKu6oRoXTid78Q9lw.png)

Now, we need to move all code from _App.js_ to _FacebookAuth.jsx_ file. The code is shown in the code snippet below:

{% gist https://gist.github.com/krissnawat/d2bd67a3b0033673dc59ed022a467590 %}

Then we need to change three things which are mentioned below:

1. First, we need to change the class name to FacebookAuth and export default.
2. Second, we need to move CSS from _App.css_ to components/FacebookAuth/index.css file.
3. Finally, we need to use props from a parent to pass configuration values to components.

Then, use the props value of firebaseConfig to initialize the firebase project as shown in the code snippet below:

```
firebase.initializeApp(this.props.firebaseConfig);
```

And in the index.js file, we will wrap it to the component as shown in the code snippet below:

{% gist https://gist.github.com/krissnawat/807832732e1257b1ec71b9735cf636ee %}

Finally, we need to change the _App.js_ file to include the component and pass firebase configuration as shown in the code snippet below:

{% gist https://gist.github.com/krissnawat/801053df86900b1c6a19cea3717bc586 %}

The work to create a component for facebook login with firebase configuration props is done.

Now, let’s move on to a Bit part and get started on Bit console to create a new collection.

#### 1. Initialize Bit on a project

Here, we create a new collection on Bit to which we are going to push all our component code.

![](https://cdn-images-1.medium.com/max/587/1*FF1zzr2tVDlxytpkbV7Cbw.png)

To successfully push the whole project to Bit, you need to follow the instructions given on the page shown below:

![](https://cdn-images-1.medium.com/max/1024/1*ccQIEhgssTq-cQdb4stu7w.png)

First, we need to install Bit CLI

> Using NPM,

> npm install bit-bin --global

Then, we need to go to the project directory in our Bit CLI and perform the commands bit init and run bit login on Bit CLI as shown in the screenshot below:

![](https://cdn-images-1.medium.com/max/715/1*y2bXTuO2sAPDSDdwiJuegw.png)

#### 2. Track components

Here, we are going to stage our component to Bit repository we created. We do this by using the command bit add src/components/FacebookAuth

The result after the command is performed is shown below in the screenshot:

![](https://cdn-images-1.medium.com/max/701/1*EKDoK0HO7nBve_i09yblOQ.png)<figcaption>4</figcaption>

#### 3. Configure a React compiler for our component

When we configure a compiler we tell Bit to capsule the component with it. Capsuling components together with their compilers gives us the freedom to use, build and test them anywhere. This includes being able to run the code in any of the applications we’d like to use the component in, as well as running it in the cloud to enable features such as the [live component playground](https://bit.dev/davidhu2000/react-spinners/pacman-loader).

```
bit import bit.envs/compilers/react --compiler
```

#### 4. Tag and export

Here, we are going to s[et a version](https://docs.bit.dev/docs/versioning-tracked-components.html) to all tracked components, and export to this collection using following bit command

bit tag --all 1.0.0

The result of the command is shown in the following screenshot:

![](https://cdn-images-1.medium.com/max/732/1*BZ6Xda7oD5C_zU1GGyE_dQ.png)

Finally, we need to perform following bit command to push our component code to bit collection that we created before:

bit export krissnawat.firebase-auth-collection

Now, our package is live on [Bit](https://bit.dev/krissnawat/firebase-auth-collection/facebook-auth). You can either install it using NPM or Yarn or, you can further develop it (get its source code) using $ bit import (on an initialized Bit workspace). The code to do that is shown below:

```
npm i @bit/krissnawat.firebase-auth-collection.facebook-auth
```

Lastly, we need to replace the component in our _App.js_ file as shown in the code snippet below:

{% gist https://gist.github.com/krissnawat/b0cace081c844c47f76a102e019e8558 %}

Finally, all our work is complete and you can run the project locally to test everything. When you run the project locally you will see the result shown in the simulation below:

![](https://cdn-images-1.medium.com/max/1024/1*yAritO6H672zTbrTfHa2HA.gif)

### Conclusion

In this tutorial, we learned how to create Facebook and Firebase app and register facebook app on Firebase. This is useful for integrating facebook login in many other projects as well. Then, we learned how to make them work together and make the code better by organizing them to component base. Components make our code simpler, easy, reusable and clean. Lastly, we made our facebook login component shareable using Bit. For the next tutorial, we will learn about building Google login component.

### Learn More

- [How to Share React UI Components between Projects and Apps](https://blog.bitsrc.io/how-to-easily-share-react-components-between-projects-3dd42149c09)
- [11 React UI Component Libraries you Should Know in 2019](https://blog.bitsrc.io/11-react-component-libraries-you-should-know-178eb1dd6aa4)
- [5 Ways to Style React Components in 2019](https://blog.bitsrc.io/5-ways-to-style-react-components-in-2019-30f1ccc2b5b)

* * *