0% found this document useful (0 votes)
147 views

React Native Auth Firebase

This document discusses how to implement phone authentication with Firebase in a React Native application. It covers setting up a Firebase project, installing the necessary Firebase and React Native Firebase packages, and includes a full code example of a phone authentication flow with phone number input, verification code input, and sign in/out functionality.

Uploaded by

rintis mardika
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
147 views

React Native Auth Firebase

This document discusses how to implement phone authentication with Firebase in a React Native application. It covers setting up a Firebase project, installing the necessary Firebase and React Native Firebase packages, and includes a full code example of a phone authentication flow with phone number input, verification code input, and sign in/out functionality.

Uploaded by

rintis mardika
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

RNFirebase Authentication – Phone Auth

How To Create One Time Password with Firebase?


1. Install
$ npm install --save react-native-firebase

2. Firebase
The first thing you'll need to have is an active Firebase project.
If you already have an existing project you can skip to the Platform Specific
Installation section.

a. Create New Project
- Visit the Firebase console.
- Click the Add project box as shown below:


- A dialog will appear as shown below
• Enter your new project name and modify the project id and region if
necessary
• Click Create Project when finished
• Your project will now be created - this can take a few seconds
• Once created click the Continue button

RNFirebase Authentication – Rintis M. S. 1


- Once created you'll be redirected to the project homepage as shown below

RNFirebase Authentication – Rintis M. S. 2


Android Installation
1. Link RNFirebase
$ Run react-native link react-native-firebase
2. Setup google-service.json
A google-services.json file contains all of the information required by the Firebase
Android SDK to connect to your Firebase project. To automatically generate the json
file, follow the instructions on the Firebase console to "Add Firebase to your app".

Once downloaded, place this file in the root of your project at android/app/google-
services.json.

In order for Android to parse this file, add the google-services gradle plugin as a
dependency to your project in the project level build.gradle file:

buildscript {
//...
dependencies {
//...
classpath 'com.google.gms:google-services:4.2.0'
}
}

To apply the plugin to your project, add the following to the VERY BOTTOM of your
app android/app/build.gradle file:

apply plugin: 'com.google.gms.google-services'

3. Add Firebase Modules


The Firebase modules need to be installed as project dependencies. In
the android/app/build.gradle file, add the following:

dependencies {
// This should be here already
implementation project(':react-native-firebase')

// Firebase dependencies
implementation "com.google.android.gms:play-services-
base:16.1.0"
implementation "com.google.firebase:firebase-core:16.0.9"

...

RNFirebase Authentication – Rintis M. S. 3


RNFirebase Auth Installation
1. Add the dependency
Add the Firebase Authentication dependency to android/app/build.gradle :

dependencies {

// ...

implementation "com.google.firebase:firebase-
auth:17.0.0"

2. Install the RNFirebase Authentication Package


Add the RNFirebaseAuthPackage to your android/app/src/main/java/com/[app
name]/MainApplication.java:

// ...
import io.invertase.firebase.RNFirebasePackage;
import io.invertase.firebase.auth.RNFirebaseAuthPackage; // <-- Add this
line

public class MainApplication extends Application implements


ReactApplication {
// ...

@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RNFirebasePackage(),
new RNFirebaseAuthPackage() // <-- Add this line
);
}
};
// ...
}

RNFirebase Authentication – Rintis M. S. 4


RNFirebase Phone Auth
1. Full Example

import React, { Component } from 'react';


import { View, Button, Text, TextInput, Image } from 'react-native';

import firebase from 'react-native-firebase';

const successImageUri =
'https://cdn.pixabay.com/photo/2015/06/09/16/12/icon-803718_1280.png';

export default class PhoneAuthTest extends Component {


constructor(props) {
super(props);
this.unsubscribe = null;
this.state = {
user: null,
message: '',
codeInput: '',
phoneNumber: '+44',
confirmResult: null,
};
}

componentDidMount() {
this.unsubscribe = firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.setState({ user: user.toJSON() });
} else {
// User has been signed out, reset the state
this.setState({
user: null,
message: '',
codeInput: '',
phoneNumber: '+44',
confirmResult: null,
RNFirebase Authentication – Rintis M. S. 5
});
}
});
}

componentWillUnmount() {
if (this.unsubscribe) this.unsubscribe();
}

signIn = () => {
const { phoneNumber } = this.state;
this.setState({ message: 'Sending code ...' });

firebase.auth().signInWithPhoneNumber(phoneNumber)
.then(confirmResult => this.setState({ confirmResult, message: 'Code has
been sent!' }))
.catch(error => this.setState({ message: `Sign In With Phone Number
Error: ${error.message}` }));
};

confirmCode = () => {
const { codeInput, confirmResult } = this.state;

if (confirmResult && codeInput.length) {


confirmResult.confirm(codeInput)
.then((user) => {
this.setState({ message: 'Code Confirmed!' });
})
.catch(error => this.setState({ message: `Code Confirm Error:
${error.message}` }));
}
};

signOut = () => {
firebase.auth().signOut();
}

renderPhoneNumberInput() {
const { phoneNumber } = this.state;

RNFirebase Authentication – Rintis M. S. 6


return (
<View style={{ padding: 25 }}>
<Text>Enter phone number:</Text>
<TextInput
autoFocus
style={{ height: 40, marginTop: 15, marginBottom: 15 }}
onChangeText={value => this.setState({ phoneNumber: value })}
placeholder={'Phone number ... '}
value={phoneNumber}
/>
<Button title="Sign In" color="green" onPress={this.signIn} />
</View>
);
}

renderMessage() {
const { message } = this.state;

if (!message.length) return null;

return (
<Text style={{ padding: 5, backgroundColor: '#000', color: '#fff'
}}>{message}</Text>
);
}

renderVerificationCodeInput() {
const { codeInput } = this.state;

return (
<View style={{ marginTop: 25, padding: 25 }}>
<Text>Enter verification code below:</Text>
<TextInput
autoFocus
style={{ height: 40, marginTop: 15, marginBottom: 15 }}
onChangeText={value => this.setState({ codeInput: value })}
placeholder={'Code ... '}
value={codeInput}
/>

RNFirebase Authentication – Rintis M. S. 7


<Button title="Confirm Code" color="#841584"
onPress={this.confirmCode} />
</View>
);
}

render() {
const { user, confirmResult } = this.state;
return (
<View style={{ flex: 1 }}>

{!user && !confirmResult && this.renderPhoneNumberInput()}

{this.renderMessage()}

{!user && confirmResult && this.renderVerificationCodeInput()}

{user && (
<View
style={{
padding: 15,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#77dd77',
flex: 1,
}}
>
<Image source={{ uri: successImageUri }} style={{ width: 100, height:
100, marginBottom: 25 }} />
<Text style={{ fontSize: 25 }}>Signed In!</Text>
<Text>{JSON.stringify(user)}</Text>
<Button title="Sign Out" color="red" onPress={this.signOut} />
</View>
)}
</View>
);
}
}

RNFirebase Authentication – Rintis M. S. 8

You might also like