Build a Mobile Phone Authentication Component with React and Firebase

Build a Mobile Phone Authentication Component with React and Firebase

Learn how to build a reusable phone authentication component with React and Firebase.

What you’ll learn …?
  • How to use Bit
  • .How to use Bit along with React.
  • How to use React router DOM (Document Object Model).
  • How to use Firebase phone authentication.
Requirements

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

  • How to use Bit
  • .How to use Bit along with React.
  • How to use React router DOM (Document Object Model).
  • How to use Firebase phone authentication.
Brief summary

Here, we have a summary of steps we are going to perform in order to implement Phone authentication component in our React project:

  • How to use Bit
  • .How to use Bit along with React.
  • How to use React router DOM (Document Object Model).
  • How to use Firebase phone authentication.
Creating React component

Firstly, we need to create a new component in src/components/PhoneAuth. Then, we need to add App.css CSS file that we got from the previous part of this tutorial series. Next, we need to create three files, an index.js for an entry point, InputPhone.jsx to handle phone number configurations and PhoneButton.jsx to display a phone button that will have the function to navigate to ***InputPhone ***component. The overall structure of directory files is shown below:

Activate Firebase Phone Authentication

Here, we need to go to the firebase console, Then, navigate to > authentication > authentication method then activate **Phone **authentication as shown in the console screenshot below:

Now, we can use Phone authentication with Firebase.

Working on component

In this step, we are going to start working on our Authentication component.

Setup react-router-dom

Here, we need to set up the react-router-dom in order to navigate to different files. We are going to use index.js file for the entry point. Then, we register a route to make navigation between ***PhoneButton ***to ***InputPhone ***components.

Firstly, we need to install react-router-dom package using the command given below:

npm install react-router-dom

Then, we need to activate react-router-dom package eat the main root index.js by importing BrowserRouter component from the react-router-dom package as shown in the code snippet below:

Here, we are importing ***BrowserRouter ***component and wrapping the ***App ***component using it.

Then, we need to copy the code below and paste to src/components/PhoneAuth/index.js.

Here, we are importing ***Switch ***and ***Route ***component from the react-router-dom package.

***Route ***component is used to define URL location and Switch component is used as a wrapper to Route component.

Then, we need to define a route for our two-components that we created before, which are ***PhoneButton ***and ***InputPhone ***components.

For the ***index ***route, we are using ***PhoneButton ***component.

For the input_phone route, we are using ***InputPhone ***component.

Now, we can navigate between these two components.

PhoneButtton.jsx

In PhoneButton.jsx file, we are going to implement a phone button. Then, we are going to use this component to display the phone button and navigate to ***InputPhone ***component.

To implement this, we need to open ***PhoneButton.jsx ***file and paste the code in the code snippet below:

Here, we are using ***Link ***component from react-router-dom in order to create a link to InputPhone Component.

Then, we import our component to App.js file and implement it to *render() *function as shown in the code snippet below:

Now, we need to start the server to see the result screen. After starting the server, we will see the following result in our screen:

InputPhone.jsx

Our main work to be done is in InputPhone component. We are going to use this component to handle sending SMS and verify OTP. For this, we need to open src/components/PhoneAuth/PhoneInput.jsx and paste the code given in the code snippet below:

Here, the code given in the code snippet above is used to construct a form and initialize firebase in our project.

Now, If we restart the server and test the screen buttons, we will get the following result:

Here, when we click on Sign in with phone button, we will get a form and verify button to verify with firebase.

Getting Form Value

In this step, we need to get the form values and set it to the internal state variables.

Here, we need to create an internal state named phone_number then attach it to Input field with this.state.value to set the value of the state.

Then, we need to create a new function named handlePhoneChange() in order to get value from the input field and when **onChange **event is fired we set a new value to the state variable.

Send SMS with Firebase

Next, we are going to implement ‘send SMS’ feature with firebase. Here, before implementing send SMS feature, we have a requirement to install Recaptcha firebase to prevent fraud and spam on their service.

For this, we need to create componentDidmount and paste the code given in the code snippet below:

Here, we need to set up CSS id named Recaptcha-container to place Recaptcha and define size, callback function with success and error. Then, we need to render on target and last assign object to window object that makes it global, and we can use the object across the function.

Then, we need to place a new divelement to the location that we want to render Recaptcha:

<div id="recaptcha-container" />

As a result, our form will appear as shown in the emulator simulation below:

For better functioning, we need to disable VERIFYbutton until **Recaptcha **is verified successfully. We can do this using the following code:

Here, we need to create a new state named isButtonDisabled and toggle the state with **Recaptcha **callback. Then, we need to place the isButtonDisabled state at the button in the disabled event as shown in the code snippet below:

As a result, the

VERIFY

button remains disabled until the Recaptcha is verified as shown in the emulator simulation below:

Now, we have the **Recaptcha **that we required for the firebase.

Next, we need to implement Phone authentication.

For this, first, we need to create a new function named handleLogin() as shown in the code snippet below:

Here, we need to grab the Recaptcha object and call signInWithPhoneNumber then pass two required parameter phone_number and ReCaptcha object i.e. appVerifier. On success, we need to print result i.e. conformationResult.

Submit form

Next, we need to implement the functionality to submit the form. But the problem is that the page reloads after we hit the submit button and submit the form. To prevent the form reload, we add function name handleSubmit()and add the function to <form> element wrapping the button we implemented before. The code for this is given in the code snippet below:

Next, in order to trigger handleLogin function, we need to add onClick event to verify the button. Now, we need to test its functionality. We can see the result of testing the button below in the simulation:

Here, we received a successful result.

Next, we need to implement the verifying process.

Verify OTP

Here, we need to verify the authentication using OTP. First, we need to store a result object to window object which makes it global and we can use the object across the function. Then, we need to set a state variable as sendOTP as shown in the code snippet below:

Here, to verify OTP, we need to create another form in the same component and toggle hide and show using sendOTP state.

For the verification process, we need to do the same on sending SMS process. First, we need to create two new state variables. For this, we can copy the code given in the code snippet below and paste to src/components/PhoneAuth/PhoneInput.jsx.

Here, sendOTP state is used for toggle between “input phone number” form and“ *verify SMS” *form. The default value of sendOTP state is false.

otp state is used to handle OTP data that we are getting from the form.

handleOTPChange() function is used in order to get form value.

handleOTPCheck function is used to check OTP object that comes from the result of handleLogin function that we mentioned before. Then, we pass OTP value from state and display the result in the console.

Next, we use sendOTP state to toggle display between **PhoneInput **form and OTP verify form. Then, we need to add the function that we created before to form and button which is same as we did in **PhoneInput **form.

Now, we have configured everything. Next, we need to check if everything is working properly.

As we can see, we can the expected result in the browser console. Next, we need to check the result in the Firebase console as well.

As we can see in the above screenshot, we get the result as expected in firebase console as well.

Finally, we have successfully implemented the Firebase phone authentication component in React.Next, we need to push our Authentication component to Bit.

Make it Reusable and Sharable with Bit

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). Then, we’ll export it (with all its dependencies), to a component collection on Bit’s cloud, to be shared with others and easily reused.

In this step, we are going to push the new component i.e. Phone Authentication component to Bit. We already have our Bit package installed and connected to our Bit account. So, we need to create a collection and start by tracking the component.

Note: The first and second step features an installation of Bit account. These steps can be skipped if you already have a Bit account.

1. Create a collection and initialize Bit on a project

Here, we need to create a new collection on Bit to which we are going to push all our component code. We use the Bit “create collection” configuration page to create a new collection named “firebase-auth-collection”.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

2. Configure a React compiler for our component

When we configure a compiler we tell Bit to capsule the component with it. Capsule components together with their compilers give 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.

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

3. Track components

We need to track our component by using the following command in your command prompt or Bit console:

bit add src/components/PhoneAuth

4. Tag and export to our collection on Bit’s cloud

Here, we are going to s

et a version

to all tracked components, and export to this collection using following bit command:

bit tag --all 0.0.1

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.

Using Bit Component

To use Bit component, we need to import Bit component using the Bit import command which is given in the code snippet below:

Here, we need to open another project and use the command:

bit import krissnawat.firebase-auth-collection/phone-auth --path src/components/PhoneAuth

Now, all the files imported should be placed in the component directory as shown below:

Now, we can use the component successfully imported from the Bit.

Update component and push back to Bit

In this section, we learn how to update component code and create a new bit component with the feature of resending OTP after 20 seconds.

First, we need to install react countdown package using the command:

yarn add react-countdown-now

Then, we need to create a conditional renderer function with a countdown.

Then, we need to include <Countdown/> component to verify form footer.

As a result, we will see the following simulation on the screen:

Now, everything is done. Next, we need to push the new component back to Bit using the command:

bit export krissnawat.test-collection

Now, as we can see, our component is live on Bit as shown below:

Recap

In this tutorial, we learned how to implement firebase phone authentication in firebase using react-router-dom along with Recaptcha. We also learned how to using Bit for reusable component and finally implemented the countdown timer. In the next chapter, we are going to implement Firebase email link authentication.

Recommended Reading

How to create a signature pad in React

Creating an Audio Player in React Native

How React Storybook can simplify component testing

Making API Calls with React Hooks

MEAN vs. MERN – What’s the Difference?

Learn how to build a full-stack MERN App using JWT authentication

Using Radio Button in React

Full-Stack JavaScript Tutorial for Beginners

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

What’s new in HTML6

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Why ReactJS is better for Web Application Development?

Why ReactJS is better for Web Application Development?

Web Application Development is the point of contact for a business in today's digital era. It is important to choose the right platform for Web Application Development to build a high end Web

Web Application Development is essential for a business in today’s digital era. Finding the right platform for Web Application Development is important for building an effective Web Application that can enhance the overall customer engagement. Here’s what makes ReactJS a better option for building your next Web Application.

How to Email authentication with React Native and Firebase

How to Email authentication with React Native and Firebase

In each and every app, you will see several kinds of authentication like login with Facebook, Google etc. But still, people prefer to entering email and password. In this tutorial, we are going to integrate Email authentication with React native and Firebase. Using firebase makes it easier to use.

Tip: Use Bit (GitHub) to easily share your React components into a reusable collection your team can use and develop across projects. Build modular apps faster as a team, save time and make life a bit easier. Give it a try.

Semantic UI components with Bit: Easily turn your components into a reusable collection

Email Authentication with React native, Firebase and Expo:

We’ll be using Expo without getting into Xcode or Android studio. Open up your terminal or command line and type in:

expo init fb-react-native-firebase

After hitting enter, you will see the screen as shown below, where you can enter the name of the app and slug. After that hit enter again.

Once the installation is complete, you will see the following screen:

We will be developing this project using VS Code. In VSC, open a new terminal, cd to your app’s folder and run <strong>yarn start</strong> .

The Expo will open a new window in the browser, as shown below. There you can see options for running the app using an android emulator or device. iOS simulator and by using a QR Code scanner. We are using an Android emulator to showcase this app.

After that, open up your emulator and use it to open the expo app.

Emulators use too much of your system’s memory. I tried using Android on Mac and it’s eating so much space.

So now we are ready to code.

Bootstrap form quickly with a native base

To design our interface faster and smoother we are using Native base for developing this app. You can check out the native base for more information. So let’s move on to the next step

Open a new terminal and run <strong>npm i native-base</strong>

Next step to import necessary Native base component to <strong>App.js</strong>

import { Container, Item, Form, Input, Button, Label } from "native-base";

And construct form interface

render() {
    return (
      <Container>
        <Form>
          <Item floatingLabel>
            <Label>Email</Label>
            <Input autoCapitalize="none" autoCorrect={false} />
          </Item>
          <Item floatingLabel>
            <Label>Password</Label>
            <Input
              secureTextEntry={true}
              autoCapitalize="none"
              autoCorrect={false}
            />
          </Item>
          <Button full rounded success>
            <Text>Login</Text>
          </Button>
        </Form>
      </Container>
    );
  }

When you save the result, you can see them instantly on the screen. This is a feature called as Hot-reloading.

A form appears on the top.

Now, form design is ready. Let’s move on to the main programming part.

Add firebase to React native project

Let’s add firebase with npm i firebaseand import firebase on App.js and then import that into our project.

import * as firebase from "firebase";

In the next step, you need to **create a firebase project. Goto firebase console **and make one as shown below:

Now grab configuration apikey which very important to access the data from the database.

And paste to App.js as shown below in the code structure.

import * as firebase from "firebase";
import { Container, Item, Form, Input, Button, Label } from "native-base";
var config = {
    apiKey: "AIzaSyDFdsjQWG8IFLXmviNqSiVZMw_ADFl5tpo",
    authDomain: "react-native-firebase-3bde9.firebaseapp.com",
    databaseURL: "https://react-native-firebase-3bde9.firebaseio.com",
    projectId: "react-native-firebase-3bde9",
    storageBucket: "react-native-firebase-3bde9.appspot.com",
     messagingSenderId: "269398778466"
};
firebase.initializeApp(config);

Now, we have successfully added firebase to our project.

Sign Up

For email authentication, we need to activate Email authentication on Firebase console.

Let’s jump back to VS Code and add a signup button to it.

<Button full rounded success style={{ marginTop: 20 }}> <Text>Signup</Text>
</Button>

Result view should be

Now we have to add signup code.

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      email: "",
      password: ""
    };
  }
  SignUp = (email, password) => {
    try {
      firebase
          .auth()
          .createUserWithEmailAndPassword(email, password)
          .then(user => { 
                 console.log(user);
           });
} catch (error) {
      console.log(error.toString(error));
    }
  };

We create a state for handle email and password from. We have created the form and SignUp function for handling firebase code.

Next, add form value to state with on ChangeText.

<Item floatingLabel>
            <Label>Email</Label>
            <Input
              autoCapitalize="none"
              autoCorrect={false}
              onChangeText={email => this.setState({ email })}
            />
          </Item>
          <Item floatingLabel>
            <Label>Password</Label>
            <Input
              secureTextEntry={true}
              autoCapitalize="none"
              autoCorrect={false}
              onChangeText={password => this.setState({ password })}
            />

And we trigger SignUp function with onPress event from Signup button.

onPress={() => this.SignUp(this.state.email, this.state.password)}

Save and try to submit a form.

After submitting the data goto firebase console and check that the data you have entered is coming there or not.

Now we have added data successfully in Firebase as a new user.

Login

For login, we use code from sign up method and change firebase function.

Login = (email, password) => {
    try {
      firebase
         .auth()
         .signInWithEmailAndPassword(email, password)
         .then(res => {
             console.log(res.user.email);
      });
} catch (error) {
      console.log(error.toString(error));
    }
  };

After you need to use the **onAuthStateChanged method **to get user data. Then add an onPress method to SignIn Buton.

onPress={() => this.LogIn(this.state.email, this.state.password)}

Let’s try signing in.

Finally we have made it. We got the data from the firebase user database.

Conclusion

In this tutorial, you have learned about how to setup react native project with expo and firebase. You have also learned, how to kickstart construct UI with NativeBase? Then after that, we have created a basic email authentication using React Native, Firebase and expo.

We hope you got something from this. Thanks for reading!

Firebase as simple database to React app

Firebase as simple database to React app

In this tutorial you're going to learn how to use Firebase Real Time Database service in React application


Firebase is an all-in-one backend as a service provider (BaaS) that provides database, authentication, cloud storage among their many services. In this tutorial you’re going to learn how to use Firebase Real Time Database service in React application.

You’re going to build a simple team list application, where users can add, delete and edit team member information.

Here is the final application:

Create your database application

First, you need to create your application in Firebase console.

Then head over to the Database menu and scroll a bit down into Choose Real Time Database section.

Set the security rules to start in test mode.

(this makes your database insecure, but it’s okay for the purpose of this tutorial.)

Finally, get the configuration needed to integrate Firebase into your web app.


Setting up your React application

Start your React application with create-react-app

npx create-react-app react-firebase-basic

Then install firebase and Bootstrap (so you can skip writing your own css.)

npm i firebase bootstrap

Then you can remove everything from src/ since you don’t need most of the boilerplates


Creating config.js file

Let’s write Firebase configuration in a separate config.js file:

const config = {
firebase:{
apiKey: "AIzaSyAgBvGKlPEySB6vCWVkyO5OnRiVP3pzgps",
authDomain: "react-firebase-basic.firebaseapp.com",
databaseURL: "https://react-firebase-basic.firebaseio.com",
}
}

export default config;

You’ll import this config into your App.js later.


Write the index.js file

This file will serve as React entry point:

import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.css';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));

Creating your application

It’s time to write your App.js file. Let’s initialize our Firebase App in the constructor:

import React from 'react';

import Firebase from 'firebase';
import config from './config';

class App extends React.Component {

constructor(props){
super(props);
Firebase.initializeApp(config.firebase);

<span class="hljs-keyword">this</span>.state = {
  developers: []
}

}

//...

Then you can write the logic for getting and saving data: writeUserdata will write our state into the database, while getUserData will create a listener on / path, and on value changes, we will assign snapshot value as state.

writeUserData = () => {
Firebase.database().ref('/').set(this.state);
console.log('DATA SAVED');
}

getUserData = () => {
let ref = Firebase.database().ref('/');
ref.on('value', snapshot => {
const state = snapshot.val();
this.setState(state);
});
console.log('DATA RETRIEVED');
}

Put these writeUserData and getUserData in componentDidMount and componentDidUpdate respectively.

componentDidMount() {
this.getUserData();
}

componentDidUpdate(prevProps, prevState) {
// check on previous state
// only write when it's different with the new state
if (prevState !== this.state) {
this.writeUserData();
}
}

All that’s left is to write the render and handle submit form logic: We will map our developers array from state and put each item in a card component. Each card will have a delete and update button. On delete clicked, we will filter out the specific item, while on update clicked, we will get the item data into the form.

handleSubmit will insert data when uid value is false and update data when it is true. We’re using refs to get data from form inputs.

// ...
render() {
const { developers } = this.state;
return(
<div className="container">
<div className="row">
<div className='col-xl-12'>
<h1>Firebase Development Team</h1>
</div>
</div>
<div className='row'>
<div className='col-xl-12'>
{
developers
.map(developer =>
<div key={developer.uid} className="card float-left" style={{width: '18rem', marginRight: '1rem'}}>
<div className="card-body">
<h5 className="card-title">{ developer.name }</h5>
<p className="card-text">{ developer.role }</p>
<button onClick={ () => this.removeData(developer) } className="btn btn-link">Delete</button>
<button onClick={ () => this.updateData(developer) } className="btn btn-link">Edit</button>
</div>
</div>
)
}
</div>
</div>
<div className='row'>
<div className='col-xl-12'>
<h1>Add new team member here</h1>
<form onSubmit={ this.handleSubmit }>
<div className="form-row">
<input type='hidden' ref='uid' />
<div className="form-group col-md-6">
<label>Name</label>
<input type="text" ref='name' className="form-control" placeholder="Name" />
</div>
<div className="form-group col-md-6">
<label>Role</label>
<input type="text" ref='role' className="form-control" placeholder="Role" />
</div>
</div>
<button type="submit" className="btn btn-primary">Save</button>
</form>
</div>
</div>
</div>
)
}

handleSubmit = (event) => {
event.preventDefault();
let name = this.refs.name.value;
let role = this.refs.role.value;
let uid = this.refs.uid.value;

if (uid && name && role){
const { developers } = this.state;
const devIndex = developers.findIndex(data => {
return data.uid === uid
});
developers[devIndex].name = name;
developers[devIndex].role = role;
this.setState({ developers });
}
else if (name && role ) {
const uid = new Date().getTime().toString();
const { developers } = this.state;
developers.push({ uid, name, role })
this.setState({ developers });
}

this.refs.name.value = '';
this.refs.role.value = '';
this.refs.uid.value = '';
}

removeData = (developer) => {
const { developers } = this.state;
const newState = developers.filter(data => {
return data.uid !== developer.uid;
});
this.setState({ developers: newState });
}

updateData = (developer) => {
this.refs.uid.value = developer.uid;
this.refs.name.value = developer.name;
this.refs.role.value = developer.role;
}

Now your React application is ready to read and set data into your Firebase database. Here is the final demo again: