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

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 Firestore, Cloud Functions, Crashlytics…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:

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:

Creating the Screens
If we take a look at our diagram, you can see that we have four screens: Loading, SignUp, Login, and Main.
A 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-navigationLet’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 AppIf 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...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...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
Post a Comment
Thank You.