Firebase is a platform for building iOS, android as well as web-based apps like in React Native. it offers storage, real-time database, authentication and user-notification, Crash Reporting,   Cloud FirestoreCloud FunctionsHostingPerformance MonitoringTest Lab for Android  etc. To know more about firebase go to firebase doc.

Firebase 3.x SDK , authentication part of the SDK was not supported. Firebase 3.1.0 SDK release replace the use of browser-specific APIs that supports again with React Native.

I am going to create very simple app for authentication using firebase. If user have already account, he can sign-in else user need to signup. You can find complete the code on GitHub , you can clone the project. Inside the project directory run command npm install  then run the app using the react-native run-android.  Follow the following instruction for complete setup.



           

Firebase Setup

Step 1:– Go to Firebase Setup . Login if you are not. or  Go to https://firebase.google.com and click on Go to Console on the top right of the Screen. You need to make sure you are using latest version of firebase.

Step 2:-  Create new project. Fill up your project name and region name.

      

Step 3:-  Click on Add Firebase to your web app.

      .

Step 4:-   After clicking Add Firebase to your web app,  a dialog box will be open. There is all credential like apiKey, authDomain, databaseURL, ProjectId, storageBucket  just copy that it will used in react-native project.

      

Step 5:- Inside the project, click to Authentication which is left side of screen. Click on SIGN-IN METHOD and enable the Email/Password option.

       

Step 6:-  After successfully signup you can see all the account on USERS tab.

      

Create  React-Native project.

The complete code for the Firebase Authentication app is on github.

Note:- You have to need to replace the firebaseconfiguration. To get the firebaseconfiguration you need to follow the above steps of firebase setup.

Step 1:- Create a new React-Native Project  using command. If you have not set up the environment you can setup from here

 react-native init  firebaseAuth

Step 2:- Install npm firebase.

npm install –save firebase

Step 3:-  Install npm react-navigation

npm install –save react-navigation

Step 4:- Create folder app inside the project. Inside the app folder create two folder.

  • app/component

Step 5:- Create the following files.

  • app/component/LoginPage.js
  • App.js

Step 6:- Replace the index.js with following code.

 

import { AppRegistry } from 'react-native';
import App from './App';

AppRegistry.registerComponent('firebaseAuth', () => App);

Step 7:- App.js  

In this file, replace firebase configuration (
apiKey, authDomain, databaseURL, projectId, storageBucket, messagingSenderId) inside the componentWillMount() function.

import React, { Component } from 'react';
import { View, Text } from 'react-native';
import Config from 'react-native-config';
import firebase from 'firebase';
import LoginPage from './app/component/LoginPage';

class App extends Component {
    componentWillMount() {
        firebase.initializeApp({
            apiKey: 'AIzaSyBkP3ovBefuls9MTZ9X176MqORlVqAlpck',
            authDomain: 'reactfirebase-e69e0.firebaseapp.com',
            databaseURL: 'https://reactfirebase-e69e0.firebaseio.com',
            projectId: 'reactfirebase-e69e0',
            storageBucket: 'reactfirebase-e69e0.appspot.com',
            messagingSenderId: '470892154345'
        });
    }
    render() {
        return (
            <View>
              <LoginPage />
            </View>            
        );
    }
}

export default App;





Step 8:-  app/component/LoginPage.js

Firebase provide the signInWithEmailAndPassword() method to sign-in and createUserWithEmailAndPassword() method to signup.

import React, { Component } from 'react';
import { View, Button, TextInput, TouchableOpacity, Text, Spinner } from 'react-native';
import firebase from 'firebase';

class LoginPage extends Component {
  constructor(props) {
    super(props);
    this.state = {
     email: '',
     password: '',
     error: ''
   };
   this.onLoginPress= this.onLoginPress.bind(this);
  }

  onLoginPress() {
        this.setState({ error: '', loading: true });
        const { email, password } = this.state;
        firebase.auth().signInWithEmailAndPassword(email, password)
            .then(() => { alert('Successful login') })
            .catch(() => {
                //Login was not successful, let's create a new account
                firebase.auth().createUserWithEmailAndPassword(email, password)
                    .then(() => { alert("Successfully Created new account") })
                    .catch(() => {
                       alert('Something wrong') 
                    });
         });
   }

  render() {
    return (
      <View>
           <Text style={styles.title} >Login with Firebase </Text>
           <TextInput
             style={{height: 40}}
             onChangeText={(email) => this.setState({email})}
             value={this.state.email}
             placeholder="Enter your email"
           />
          <TextInput
            style={{height: 40, borderColor: 'gray', borderWidth: 1}}
            secureTextEntry={true}
            onChangeText={(password) => this.setState({password})}
            value={this.state.password}
            placeholder="Enter your password"
           />
           <TouchableOpacity onPress={this.onLoginPress}>
             <View style={styles.loginView}>
               <Text style={styles.loginText}>LogIn/Signup</Text>
              </View>
           </TouchableOpacity>
        </View>
    );
  }
}
const styles = {
    errorTextStyle: {
      color: '#E64A19',
      alignSelf: 'center',
      paddingTop: 10,
      paddingBottom: 10
    },
    loginView: {
      margin: 20,
      height: 40,
      backgroundColor:'#E64A19',
      alignItems: 'center',
      justifyContent: 'center',
    },
    loginText: {
      color: '#fff',
    },
    title: {
      alignSelf: 'center',
      margin: 40,
      fontSize: 20,
    }
};
export default LoginPage;

Feel free to comment if you have any issue.

Leave a Reply

Your email address will not be published. Required fields are marked *