How to implement Forgot Password feature in React Native with Firebase

Published on Oct 25, 2019

8 min read

EXPO

Originally published at Heartbeat.Fritz.ai

In some of the previous posts, you built a React Native app using Firebase as the backend service provider for Email authentication and storing user data upon successful sign-up.

Let's add another common yet useful and necessary feature in the current app structure: Forgot Password. This feature will require another screen in the current React Native app. To follow this tutorial, you can go through the previous posts if you are a beginner to the React Native world:

Or you if you are comfortable in understanding React Native code, dive deep in source code or download it from the Github repo release here.

After downloading the source code, please navigate inside the project directory and install dependencies by running the command npm install or yarn install.

Table of Contents

🔗
  • Requirements
  • Add Forgot Password Screen
  • Add a method to send a password reset email
  • Create a Form
  • Handle Password Reset

Requirements

🔗

To follow this tutorial, please make sure you the following libraries are installed on your local development environment and access to the services mentioned below.

  • Nodejs (>= 12.x.x) with npm/yarn installed
  • Expo SDK (>= 40.x.x)
  • Firebase account, free tier will do

Add Forgot Password Screen

🔗

Let’s start with a basic screen and hook it up with current navigation flow such that an app user will be able to navigate to this new screen from the Login screen.

Create a new file screens/ForgotPassword.js with some dummy text.

1import React, { Component } from 'react';
2import { Text, View } from 'react-native';
3
4class ForgotPassword extends Component {
5 render() {
6 return (
7 <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
8 <Text>Forgot Password Screen</Text>
9 </View>
10 );
11 }
12}
13
14export default ForgotPassword;

Open the AuthNavigation.js file and this new class component as below.

1import { createStackNavigator } from 'react-navigation-stack';
2import Login from '../screens/Login';
3import Signup from '../screens/Signup';
4import ForgotPassword from '../screens/ForgotPassword';
5
6const AuthNavigation = createStackNavigator(
7 {
8 Login: { screen: Login },
9 Signup: { screen: Signup },
10 ForgotPassword: { screen: ForgotPassword }
11 },
12 {
13 initialRouteName: 'Login',
14 headerMode: 'none'
15 }
16);
17
18export default AuthNavigation;

Lastly, open Login.js file. Logically, this where a button to navigate to this new ForgotPassword component should exist. First, add the handler method goToForgotPassword inside the Login class component with other handler methods.

1goToForgotPassword = () => this.props.navigation.navigate('ForgotPassword');

Passing the name of the route as the first parameter to navigation.navigate() is how you navigate from one screen to the other screen using react-navigation library. In this case, the name of the route is going to be ForgotPassword.

Next, add the a Button component after the Signup button. The value of the onPress prop of this button is going to be the handler method.

1<Button
2 title="Forgot Password?"
3 onPress={this.goToForgotPassword}
4 titleStyle={{
5 color: '#039BE5'
6 }}
7 type="clear"
8/>

Now, open a simulator or a real device with an Expo client installed and run the command expo start from a terminal window. You will be welcomed by the following screen.

ss1

Clicking on the button Forgot Password ? will lead you to the new screen.

ss2

Add a method to send a password reset email

🔗

The Firebase authentication module provides a method that you can use in React Native apps to send a link to the user's registered email id with the app. Users can click the link to reset the password. Firebase does this on its own. You do not have to write the server code to add this functionality to your app.

To start, open config/Firebase/firebase.js file and add the following method. You will use this method inside the ForgotPassword component by providing the user's email as input.

1passwordReset: email => {
2 return firebase.auth().sendPasswordResetEmail(email)
3},

That's all you need to configure the Firebase app to make sure it sends the email on the registered email id.

To extend this further, you can try and customize the Email template that Firebase uses to send the reset password link here.

Create a Form

🔗

Using the previously obtained knowledge of Formik ad yup let us add an input field and a button. The input field will take in the email and the button will be responsible to perform the action of submitting the form. In other words, it will trigger the network to reset the user's email in a handler method.

Open ForgotPassword.js file and add the following import statements.

1import React, { Component, Fragment } from 'react';
2import { Text, SafeAreaView, View, StyleSheet } from 'react-native';
3import { Formik } from 'formik';
4import * as Yup from 'yup';
5import FormInput from '../components/FormInput';
6import FormButton from '../components/FormButton';
7import ErrorMessage from '../components/ErrorMessage';
8import { withFirebaseHOC } from '../config/Firebase';

After the import statements, add validationSchema object. This object is similar to that used in Login component and will help to determine whether the input provided already exists as the registered email or not.

1const validationSchema = Yup.object().shape({
2 email: Yup.string()
3 .label('Email')
4 .email('Enter a valid email')
5 .required('Please enter a registered email')
6});

Go the render function, and replace its existing content to the form below.

1render() {
2 return (
3 <SafeAreaView style={styles.container}>
4 <Text style={styles.text}>Forgot Password?</Text>
5 <Formik
6 initialValues={{ email: '' }}
7 onSubmit={(values, actions) => {
8 this.handlePasswordReset(values, actions)
9 }}
10 validationSchema={validationSchema}>
11 {({
12 handleChange,
13 values,
14 handleSubmit,
15 errors,
16 isValid,
17 touched,
18 handleBlur,
19 isSubmitting
20 }) => (
21 <Fragment>
22 <FormInput
23 name='email'
24 value={values.email}
25 onChangeText={handleChange('email')}
26 placeholder='Enter email'
27 autoCapitalize='none'
28 iconName='ios-mail'
29 iconColor='#2C384A'
30 onBlur={handleBlur('email')}
31 />
32 <ErrorMessage errorValue={touched.email && errors.email} />
33 <View style={styles.buttonContainer}>
34 <FormButton
35 buttonType='outline'
36 onPress={handleSubmit}
37 title='Send Email'
38 buttonColor='#039BE5'
39 disabled={!isValid || isSubmitting}
40 />
41 </View>
42 <ErrorMessage errorValue={errors.general} />
43 </Fragment>
44 )}
45 </Formik>
46 </SafeAreaView>
47 )
48 }

In the above code snippet, the elements such as FormInput, FormButton and ErrorMessage are some re-usable custom presentational components that you can find inside components/ directory. this.handlePasswordReset(values, actions) is the handler method that accepts two parameters. You will write the logic behind this method in the next section.

The corresponding styles to the component are:

1const styles = StyleSheet.create({
2 container: {
3 flex: 1,
4 backgroundColor: '#fff',
5 marginTop: 150
6 },
7 text: {
8 color: '#333',
9 fontSize: 24,
10 marginLeft: 25
11 },
12 buttonContainer: {
13 margin: 25
14 }
15});

Lastly, do not forget to wrap the ForgotPassword with the Firebase High Order Component withFirebaseHOC to use passwordReset method as props.

1export default withFirebaseHOC(ForgotPassword);

Now go back to the simulator and you will get the following screen.

ss3

Handle Password Reset

🔗

Inside the ForgotPassword component create a new handler method called handlePasswordReset. This is going to be an asynchronous function that will accept the user's email as the parameter from the Formik's values.

Also, pass the actions from Formik as the second parameter. Instead of just console logging the error values, to display the error on the screen, Formik provides setFieldError.

1handlePasswordReset = async (values, actions) => {
2 const { email } = values;
3
4 try {
5 await this.props.firebase.passwordReset(email);
6 console.log('Password reset email sent successfully');
7 this.props.navigation.navigate('Login');
8 } catch (error) {
9 actions.setFieldError('general', error.message);
10 }
11};

The above snippet signifies that if the email provided as the input is valid, it will send the request to reset the password. On success, a message on Expo's console will be displayed as shown below.

ss4

Also, on success, it will navigate the user back to the login screen. On errors, the code inside the catch block will be triggered.

To try it out, register a user with a valid email address such that you can receive an email. On registering a new user, right now, the app will log you in. Sign out from the app which will take you back to the login screen. Next, go the Forgot Password screen and enter the valid email.

ss8

You will receive an email like the below. It uses the default Firebase template. To demonstrate, I am using my personal Gmail address.

ss5

Click on the link and it will redirect you to a webpage like below.

ss6

Upon successful password change, it will prompt with the following message to the user.

ss7

Conclusion

🔗

That's it! It is that simple. With a new password, you can try to login to the app now and it will work. If you have come this far, I am hope enjoyed reading this post. These are some of the strategies I try to follow with any Firebase + React Native projects.

I hope any of the codebase used in this tutorial helps you. To find the complete code, you will have to visit this Github repo release.

Further reading

🔗

More Posts

Browse all posts

Aman Mittal author

I'm a software developer and a technical writer. On this blog, I write about my learnings in software development and technical writing.

Currently, working maintaining docs at 𝝠 Expo. Read more about me on the About page.


Copyright ©  2019-2024 Aman Mittal · All Rights Reserved.