Skip to main content

React Native and Firebase: Authentication

 

React Native and Firebase: Authentication

How to set up your React Native app to work with Firebase

Authenticate a User in React with Firebase

https://next.egghead.io/lessons/react-authenticate-a-user-in-react-with-firebase

Photo by Google...

Hi! I’m Sanjay. Here’s a quick guide that will get us up and running with Firebase’s Authentication in React Native!

Firebase provides a lot of great products that allow us to develop mobile apps quickly; Realtime Database, Authentication, Cloud FirestoreCloud FunctionsCrashlytics…Just to name a few.

We’re going to be building a simple authentication flow using an email and password.

All we need is a way to use the Firebase SDK with a React Native app…and thanks to the lovely people at Invertase, who created react-native-firebase, we have just that! It’s an awesome open-source project for linking React Native apps with Firebase.

Setting Up Our App

Since we’re starting from scratch, we can go ahead and use the basic starter kit provided by react-native-firebase.

(If you already have an existing application, you can head over to React Native Firebase and follow the manual installation instructions.)

Go ahead and follow their instructions (they’re great) to get our app up and running, and then come back when you’re ready.

Enable Email and Password Authentication in Firebase

After following the instructions linked above, you should be ready to get started.

Here’s a diagram of what we’re going to be building:

A flow diagram of what we’re building

To allow users to use an email and password combo, we need to enable this provider in our Firebase console.

To do this, head on over to your Firebase Project → Authentication → Sign-in Method. Click on Email/Password and set to enabled and save. Your dashboard should look like this:

Enabling email and password authentication

Creating the Screens

If we take a look at our diagram, you can see that we have four screens: LoadingSignUpLogin, and Main.

Loading screen that displays until we determine the auth state of a user, a SignUp screen where the user can create an account, a Login screen where an existing user can log in, and a Main screen of our application that we only show to an authenticated user.

We’re going to be using react-navigation for our app’s navigation, so let’s set up our navigator and create our screens.

yarn add react-navigation

Let’s create our screens.

Loading.js

// Loading.js
import React from 'react'
import { View, Text, ActivityIndicator, StyleSheet } from 'react-native'
export default class Loading extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text>Loading</Text>
        <ActivityIndicator size="large" />
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  }
})

SignUp.js



// SignUp.js
import React from 'react'
import { StyleSheet, Text, TextInput, View, Button } from 'react-native'
export default class SignUp extends React.Component {
  state = { email: '', password: '', errorMessage: null }
handleSignUp = () => {
  // TODO: Firebase stuff...
  console.log('handleSignUp')
}
render() {
    return (
      <View style={styles.container}>
        <Text>Sign Up</Text>
        {this.state.errorMessage &&
          <Text style={{ color: 'red' }}>
            {this.state.errorMessage}
          </Text>}
        <TextInput
          placeholder="Email"
          autoCapitalize="none"
          style={styles.textInput}
          onChangeText={email => this.setState({ email })}
          value={this.state.email}
        />
        <TextInput
          secureTextEntry
          placeholder="Password"
          autoCapitalize="none"
          style={styles.textInput}
          onChangeText={password => this.setState({ password })}
          value={this.state.password}
        />
        <Button title="Sign Up" onPress={this.handleSignUp} />
        <Button
          title="Already have an account? Login"
          onPress={() => this.props.navigation.navigate('Login')}
        />
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  textInput: {
    height: 40,
    width: '90%',
    borderColor: 'gray',
    borderWidth: 1,
    marginTop: 8
  }
})

Login.js

// Login.js
import React from 'react'
import { StyleSheet, Text, TextInput, View, Button } from 'react-native'
export default class Login extends React.Component {
  state = { email: '', password: '', errorMessage: null }
  handleLogin = () => {
    // TODO: Firebase stuff...
    console.log('handleLogin')
  }
  render() {
    return (
      <View style={styles.container}>
        <Text>Login</Text>
        {this.state.errorMessage &&
          <Text style={{ color: 'red' }}>
            {this.state.errorMessage}
          </Text>}
        <TextInput
          style={styles.textInput}
          autoCapitalize="none"
          placeholder="Email"
          onChangeText={email => this.setState({ email })}
          value={this.state.email}
        />
        <TextInput
          secureTextEntry
          style={styles.textInput}
          autoCapitalize="none"
          placeholder="Password"
          onChangeText={password => this.setState({ password })}
          value={this.state.password}
        />
        <Button title="Login" onPress={this.handleLogin} />
        <Button
          title="Don't have an account? Sign Up"
          onPress={() => this.props.navigation.navigate('SignUp')}
        />
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  textInput: {
    height: 40,
    width: '90%',
    borderColor: 'gray',
    borderWidth: 1,
    marginTop: 8
  }
})

Main.js

// Main.js
import React from 'react'
import { StyleSheet, Platform, Image, Text, View } from 'react-native'
export default class Main extends React.Component {
  state = { currentUser: null }
render() {
    const { currentUser } = this.state
return (
      <View style={styles.container}>
        <Text>
          Hi {currentUser && currentUser.email}!
        </Text>
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  }
})

Now that we have all our screens created, let’s wire up our navigation inside our App.js file.

App.js



import React from 'react'
import { StyleSheet, Platform, Image, Text, View } from 'react-native'
import { SwitchNavigator } from 'react-navigation'
// import the different screens
import Loading from './Loading'
import SignUp from './SignUp'
import Login from './Login'
import Main from './Main'
// create our app's navigation stack
const App = SwitchNavigator(
  {
    Loading,
    SignUp,
    Login,
    Main
  },
  {
    initialRouteName: 'Loading'
  }
)
export default App
If we start up our app, you should see our Loading screen with the ActivityIndicator spinning forever. This is what we expected, because we need to determine if the user is authenticated or not to determine where to route them.

If the user is authenticated, route them to the Main screen. Otherwise, send them to the SignUp screen.

Determining if a User Is Authenticated

We can use Firebase to determine the authentication state of a user. Let’s add a check on our Loading screen that determines if a user is logged in or not.


// Loading.js
// Omitted other imports...
import firebase from 'react-native-firebase'
export default class Loading extends React.Component {
  componentDidMount() {
    firebase.auth().onAuthStateChanged(user => {
      this.props.navigation.navigate(user ? 'Main' : 'SignUp')
    })
  }
// Omitted the rest of the file...
We are using Firebase’s onAuthStateChanged listener to get the current auth state of the user. If they are authenticated, we route them to the Main screen. Otherwise, we send them to the SignUp screen.

Now, since we’re not logged in, you should see the Loading screen for a brief moment, and then be routed to the SignUp screen.

Signing a User Up

We need to create a new user, so we can log them in! Let’s head on over to the SignUp screen and wire up our handleSignUp method.


// SignUp.js
// Omitted other imports...
import firebase from 'react-native-firebase'
export default class SignUp extends React.Component {
  state = { email: '', password: '', errorMessage: null }
  handleSignUp = () => {
    firebase
      .auth()
      .createUserWithEmailAndPassword(this.state.email, this.state.password)
      .then(() => this.props.navigation.navigate('Main'))
      .catch(error => this.setState({ errorMessage: error.message }))
  }
// Omitted the rest of the file...
When a user submits the form, we createUserWithEmailAndPassword and then navigate them to the Main screen. If there is an error we catch it and display it.

Displaying the Current User on the Main Screen

With our current implementation, we will only see the Main screen if a user is logged in. We need to grab the currentUser from Firebase so that we can display their email. Let’s update our Main screen do handle this.

// Main.js
// Omitted other imports...
import firebase from 'react-native-firebase'
export default class Main extends React.Component {
  state = { currentUser: null }
  componentDidMount() {
    const { currentUser } = firebase.auth()
    this.setState({ currentUser })
}
// Omitted the rest of the file...


Now, when we see the Main screen, we should see the user’s email address. If we refresh the app, we should be automatically routed to the Main screen because are already authenticated.

The last step is that we should be able to log in a user after we have already created an account!

Logging an Already Existing User In

Homestretch! Let’s update our Login screen so that we can log in with an existing account.


// Login.js
// Omitted other imports...
import firebase from 'react-native-firebase'
export default class Login extends React.Component {
  state = { email: '', password: '', errorMessage: null }
  handleLogin = () => {
    const { email, pasword } = this.state
    firebase
      .auth()
      .signInWithEmailAndPassword(email, password)
      .then(() => this.props.navigation.navigate('Main'))
      .catch(error => this.setState({ errorMessage: error.message }))
  }
// Omitted the rest of the file...

We now have a simple authentication flow set up with React Native and Firebase. If you would like access to the entire source code, I’ve uploaded it to GitHub.

Thanks for reading!

Comments

Popular Posts

How I Reduced the Size of My React Native App by 85%

How and Why You Should Do It I borrowed 25$ from my friend to start a Play Store Developer account to put up my first app. I had already created the app, created the assets and published it in the store. Nobody wants to download a todo list app that costs 25mb of bandwidth and another 25 MB of storage space. So today I am going to share with you how I reduced the size of Tet from 25 MB to around 3.5 MB. Size Matters Like any beginner, I wrote my app using Expo, the awesome React Native platform that makes creating native apps a breeze. There is no native setup, you write javascript and Expo builds the binaries for you. I love everything about Expo except the size of the binaries. Each binary weighs around 25 MB regardless of your app. So the first thing I did was to migrate my existing Expo app to React Native. Migrating to React Native react-native init  a new project with the same name Copy the  source  files over from Expo project Install all de...

How to recover data of your Android KeyStore?

These methods can save you by recovering Key Alias and Key Password and KeyStore Password. This dialog becomes trouble to you? You should always keep the keystore file safe as you will not be able to update your previously uploaded APKs on PlayStore. It always need same keystore file for every version releases. But it’s even worse when you have KeyStore file and you forget any credentials shown in above box. But Good thing is you can recover them with certain tricks [Yes, there are always ways]. So let’s get straight to those ways. 1. Check your log files → For  windows  users, Go to windows file explorer C://Users/your PC name/.AndroidStudio1.4 ( your android studio version )\system\log\idea.log.1 ( or any old log number ) Open your log file in Notepad++ or Any text editor, and search for: android.injected.signing and if you are lucky enough then you will start seeing these. Pandroid.injected.signing.store.file = This is  file path where t...

React Native - Text Input

In this chapter, we will show you how to work with  TextInput  elements in React Native. The Home component will import and render inputs. App.js import React from 'react' ; import Inputs from './inputs.js' const App = () => { return ( < Inputs /> ) } export default App Inputs We will define the initial state. After defining the initial state, we will create the  handleEmail  and the  handlePassword  functions. These functions are used for updating state. The  login()  function will just alert the current value of the state. We will also add some other properties to text inputs to disable auto capitalisation, remove the bottom border on Android devices and set a placeholder. inputs.js import React , { Component } from 'react' import { View , Text , TouchableOpacity , TextInput , StyleSheet } from 'react-native' class Inputs extends Component { state = { ...