React Native Tutorial: Using Firebase Email Authentication or Login

React Native Tutorial: Using Firebase Email Authentication or Login

In this React Native step by step tutorial, we will show you an example of using Firebase email authentication or log in with React Native iOS and Android apps. We will use the latest React Hooks and React Native Firebase library to develop this login app. A comprehensive step by step React Native tutorial on authentication or login using Firebase email authentication.

A comprehensive step by step React Native tutorial on authentication or login using Firebase email authentication

In this React Native step by step tutorial, we will show you an example of using Firebase email authentication or log in with React Native iOS and Android apps. The environment is very simple, just React Native mobile apps as a client and Firebase email authentication as a server. We will use the latest React Hooks and React Native Firebase library to develop this login app.

This tutorial divided into several steps:

  • Step #1: Setup Google Firebase Email Authentication
  • Step #2: Create a New React Native Apps
  • Step #3: Install and Configure React Native Firebase
  • Step #4: Add React Navigation Header and Pages
  • Step #5: Implementing Firebase Email Login
  • Step #6: Implementing Firebase Email Register
  • Step #7: Implementing Firebase Email Reset Password
  • Step #8: Implementing a Secure Home Screen
  • Step #9: Run and Test React Native Firebase Email Login App

The scenario for this React Native Firebase Email tutorial is very simple. Just a login page/screen, register screen, reset password screen and home screen as a secure screen for the successful login landing page. The flow described in this diagram:

The following tools, frameworks, and libraries are required for this tutorial:

  1. Node.js (NPM or Yarn)
  2. React Native
  3. Google Firebase
  4. React Native Firebase library
  5. Android Studio or SDK for Android
  6. XCode for iOS
  7. Terminal (OSX/Linux) or Command Line (Windows)
  8. Text Editor or IDE (We are using Visual Studio Code)

Before start to the main steps, make sure that you have installed Node.js and can run npm in the terminal or command line. To check the existing or installed Node.js environment open the terminal/command line then type this command.

node -v
v8.12.0
npm -v
6.4.1
yarn -v
1.10.1
Step #1: Setup Google Firebase Email Authentication

We have to go to the Google Firebase Console https://console.firebase.google.com/ to set up the Firebase email authentication. After login using your Gmail account, it will be redirected to the Firebase welcome page.

Click the "Create a Project" button then enter the project name (ours: "My React Native").

Click the "Continue" button then disable the Google analytics for this project.

Click the "Create Project" button then click the "Continue" button after the new Project is ready. Now, you will be redirected to the dashboard of the new project.

Next, choose to Develop -> Authentication on the left pane.

Click on the "Sign-in Method" tab then click Email/Password.

Click the "Enable" switch then click the "Save" button. Now, you will see the "Email/Password" enabled. Next, click the "Gear" button on the left pane then click Project Settings.

To set up iOS Apps, scroll down the Settings pane then click the iOS icon button.

Fill the iOS bundle ID that registered in your Apple Developer account then click the "Register App" button. Click "Download GoogleService-Info.plist" button to download the configuration file for iOS app then click the "Next" button few times until the end of the wizard step.

Click the "Continue to console" button. To set up Android apps, scroll down then click the "Add app" button then click the "Android icon" button.

Click the "Register App" button then click the "Download google-service.json" button to download the Android Firebase configuration file. Click the "Next" button few times until the end of the wizard steps.

Click the "Continue to console" button. Now, the Google Firebase email authentication is ready to use.

Step #2: Create a New React Native Apps

We will use React Native CLI to create a new React Native app. To install it, type this command in your App projects folder.

sudo npm install -g react-native-cli

Then create a React Native App using this command from your project directory.

react-native init RNEmailAuth

Next, go to the newly created React App folder and run the React Native app to the iOS simulator.

cd RNEmailAuth && npx react-native run-ios

Or run to the Android device/emulator.

cd RNEmailAuth && npx react-native run-android

When a new terminal window opened, go to the React Native project folder then run the Metro bundler server.

cd ~/Apps/RNEmailAuth && yarn start

Now, you will see this in the iOS simulator.

Next, we will change the iOS and Android package name or bundle ID to match the Firebase configuration files. For iOS, open the ios/RNEmailAuth.xcworkspace file using XCode.

Just change the Bundle Identifier (ours: com.djamware.rnemailauth) and it ready to use with the Firebase Authentication Email/Password.

For Android a little tricky, first, change the source folders which previously android/app/src/main/java/com/rnemailauth become android/app/src/main/java/com/djamware/rnemailauth.

Next, open and edit android/app/src/main/java/com/djamware/rnemailauth/MainActivity.java and MainApplication.java then replace this package name.

package com.rnemailauth;

to

package com.djamware.rnemailauth;

Next, open and edit android/app/src/main/AndroidManifest.xml then change this line.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.rnemailauth">

To

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.djamware.rnemailauth">

Next, open edit android/app/build.gradle then change the application ID to the new package.

android {
  ...

  defaultConfig {
      applicationId "com.djamware.rnemailauth"
      minSdkVersion rootProject.ext.minSdkVersion
      targetSdkVersion rootProject.ext.targetSdkVersion
      versionCode 1
      versionName "1.0"
  }
  ...
}

Next, open and edit android/app/BUCK then change the android_build_config and android_resource package name.

android_build_config(
    name = "build_config",
    package = "com.djamware.rnemailauth",
)

android_resource(
    name = "res",
    package = "com.djamware.rnemailauth",
    res = "src/main/res",
)

Finally, run this command from the android folder to clean up the Gradle.

./gradlew clean
Step #3: Install and Configure React Native Firebase

To make integration easier, we use the RNFirebase Authentication module https://github.com/invertase/react-native-firebase/tree/master/packages/auth for accessing Firebase Authentication from the React Native apps. For that, type this command to install the module.

yarn add @react-native-firebase/app @react-native-firebase/auth

Setup React Native Firebase on iOS

To make this React Native Firebase Authentication working on iOS devices, make sure you have XCode Signing Development Team. Otherwise, you only can run this iOS app on the simulator.

Next, open the ios/RNEmailAuth.xcworkspace from the XCode then add the previously downloaded GoogleService-Info.plist to the XCode project name.

After added to the XCode project will be like this.

Next, open and edit ios/Podfile then add this line of RNFBAuth.

target 'app' do
  ...
  pod 'RNFBAuth', :path => '../node_modules/@react-native-firebase/auth'
end

Next, run the Pod installation with repo-update after going to the ios folder.

cd ios && pod install --repo-update

Next, open and edit RNEmailAuth/AppDelegate.m then add these import of the Firebase.

#import <Firebase.h>

At the beginning of the **didFinishLaunchingWithOptions:(NSDictionary *)launchOptions** method add this line to initialize Firebase.

[FIRApp configure];

Setup React Native Firebase on Android

Copy the previously downloaded google-services.json to android/app/ folder.

cp ~/Downloads/google-services.json android/app/

Next, open and edit android/build.gradle then add this line inside the dependencies body.

dependencies {
    ...
    classpath("com.google.gms:google-services:4.2.0")
}

Next, open and edit android/app/build.gradle the add this line at the bottom of the file.

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

That it's, all configuration was auto-linked when to add @react-native-firebase/app and @react-native-firebase/auth. If not auto-link, you can do a manual link like this.

react-native link @react-native-firebase/app
react-native link @react-native-firebase/auth
Step #4: Add React Navigation Header and Pages

Before implementing the Firebase Authentication email password login, we need to add pages for login, register, and home. For that, start your IDE to create those files. If you are using Visual Studio Code, type this command in the terminal at the root of this project folder.

code .

Create a folder for those files first then create files for login, register, and home.

mkdir components
touch components/Login.js
touch components/Register.js
touch components/Home.js
touch components/Reset.js

Open and edit components/Login.js then add these lines of React Hooks codes and disable Navigation header.

import React, { useState, useEffect } from 'react';
import { Button, View, Text } from 'react-native';

export default function Login({ navigation }) {

    return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <Text>Login</Text>
        </View>
    );
}

Login.navigationOptions = ({ navigation }) => ({
    title: 'Login',
    headerShown: false,
});

Open and edit components/Register.js then add these lines of React Hooks codes and disable Navigation header.

import React, { useState, useEffect } from 'react';
import { Button, View, Text } from 'react-native';

export default function Register({ navigation }) {

    return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <Text>Register</Text>
        </View>
    );
}

Register.navigationOptions = ({ navigation }) => ({
    title: 'Register',
    headerShown: false,
});

Open and edit components/Home.js then add these lines of React Hooks codes.

import React, { useState, useEffect } from 'react';
import { Button, View, Text } from 'react-native';

export default function Home({ navigation }) {

    return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <Text>Home</Text>
        </View>
    );
}

Home.navigationOptions = ({ navigation }) => ({
    title: 'Home',
});

Open and edit components/Reset.js then add these lines of React Hooks codes and disable Navigation header.

import React, { useState, useEffect } from 'react';
import { Button, View, Text } from 'react-native';

export default function Reset({ navigation }) {

    return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <Text>Reset</Text>
        </View>
    );
}

Reset.navigationOptions = ({ navigation }) => ({
    title: 'Reset',
    headerShown: false,
});

Next, we will add the Navigation header in the screen layout for this Mobile Apps. For that, add the libraries of React Navigation and React Native Gesture Handler by type these commands.

yarn add react-navigation react-navigation-stack react-native-safe-area-context @react-native-community/masked-view react-native-gesture-handler

For iOS, go to the ios folder then install Pod.

cd ios && pod install

Next, we will implement stack navigation in the current App.js. Open and edit App.js then add these imports of react-navigation createAppContainer, react-navigation-stack createStackNavigator, log in, Register, and Home.

import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import Login from './components/Login';
import Register from './components/Register';
import Home from './components/Home';
import Reset from './components/Reset';

Add a constant variable after the imports that initialize createStackNavigator.

const RootStack = createStackNavigator(
  {
    Login: Login,
    Register: Register,
    Home: Home,
    Reset: Reset,
  },
  {
    initialRouteName: 'Home',
    defaultNavigationOptions: {
      headerStyle: {
        backgroundColor: '#19AC52',
      },
      headerTintColor: '#fff',
      headerTitleStyle: {
        fontWeight: 'bold',
      },
    },
  },
);

Add the above createStackNavigator to the createAppContainer.

const RootContainer = createAppContainer(RootStack);

Replace the current main function and the export with this export function.

export default function App() {
  return (
    <RootContainer />
  )
}
Step #5: Implementing Firebase Email Login

The login screen will contain Email, Password Input Text, login, Register, and Reset Password Button. The action of the Login button will log in the entered email and password to Firebase authentication. Register and Reset button will redirect to Register and Reset screen.

We will use additional elements to build the login, register and reset forms. For that, type this command to install the react-native-elements and react-native-vector-icons modules.

yarn add react-native-elements react-native-vector-icons

To make the react-native-vector-icons working on iOS, open and edit ios/RNEmailAuth/Info.plist then add these lines of UIAppFonts before the end of .

<dict>
    ...
    <key>UIAppFonts</key>
    <array>
        <string>AntDesign.ttf</string>
        <string>Entypo.ttf</string>
        <string>EvilIcons.ttf</string>
        <string>Feather.ttf</string>
        <string>FontAwesome.ttf</string>
        <string>FontAwesome5_Brands.ttf</string>
        <string>FontAwesome5_Regular.ttf</string>
        <string>FontAwesome5_Solid.ttf</string>
        <string>Foundation.ttf</string>
        <string>Ionicons.ttf</string>
        <string>MaterialIcons.ttf</string>
        <string>MaterialCommunityIcons.ttf</string>
        <string>SimpleLineIcons.ttf</string>
        <string>Octicons.ttf</string>
        <string>Zocial.ttf</string>
    </array>
</dict>

Next, open and edit components/Login.js then add/replace these imports of the required elements and Firebase auth.

import React, { useState } from 'react';
import { StyleSheet, ActivityIndicator, View, Text, Alert } from 'react-native';
import { Button, Input, Icon } from 'react-native-elements';
import auth from '@react-native-firebase/auth';

Add the required useState constant variable at the first line of the Login function body.

const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [showLoading, setShowLoading] = useState(false);

Add a function of Firebase login with email and password after those constants.

const login = async() => {
    setShowLoading(true);
    try {
        const doLogin = await auth().signInWithEmailAndPassword(email, password);
        setShowLoading(false);
        if(doLogin.user) {
            navigation.navigate('Home');
        }
    } catch (e) {
        setShowLoading(false);
        Alert.alert(
            e.message
        );
    }
};

Modify these views after the login function to implementing the Login Form UI.

return (
    <View style={styles.container}>
        <View style={styles.formContainer}>
            <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center'}}>
                <Text style={{ fontSize: 28, height: 50  }}>Please Login!</Text>
            </View>
            <View style={styles.subContainer}>
                <Input
                    style={styles.textInput}
                    placeholder='Your Email'
                    leftIcon={
                        <Icon
                        name='mail'
                        size={24}
                        />
                    }
                    value={email}
                    onChangeText={setEmail}
                />
            </View>
            <View style={styles.subContainer}>
                <Input
                    style={styles.textInput}
                    placeholder='Your Password'
                    leftIcon={
                        <Icon
                        name='lock'
                        size={24}
                        />
                    }
                    secureTextEntry={true}
                    value={password}
                    onChangeText={setPassword}
                />
            </View>
            <View style={styles.subContainer}>
                <Button
                    style={styles.textInput}
                    icon={
                        <Icon
                            name="input"
                            size={15}
                            color="white"
                        />
                    }
                    title="Login"
                    onPress={() => login()} />
            </View>
            <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
                <Text>Forgot Password?</Text>
            </View>
            <View style={styles.subContainer}>
                <Button
                    style={styles.textInput}
                    icon={
                        <Icon
                            name="refresh"
                            size={15}
                            color="white"
                        />
                    }
                    title="Reset Password"
                    onPress={() => {
                        navigation.navigate('Reset');
                    }} />
            </View>
            <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
                <Text>Not a user?</Text>
            </View>
            <View style={styles.subContainer}>
                <Button
                    style={styles.textInput}
                    icon={
                        <Icon
                            name="check-circle"
                            size={15}
                            color="white"
                        />
                    }
                    title="Register"
                    onPress={() => {
                        navigation.navigate('Register');
                    }} />
            </View>
            {showLoading &&
                <View style={styles.activity}>
                    <ActivityIndicator size="large" color="#0000ff" />
                </View>
            }
        </View>
    </View>
);

Finally, add these lines of styles after the navigationOptions.

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    formContainer: {
        height: 400,
        padding: 20
    },
    subContainer: {
        marginBottom: 20,
        padding: 5,
    },
    activity: {
        position: 'absolute',
        left: 0,
        right: 0,
        top: 0,
        bottom: 0,
        alignItems: 'center',
        justifyContent: 'center'
    },
    textInput: {
        fontSize: 18,
        margin: 5,
        width: 200
    },
})
Step #6: Implementing Firebase Email Register

The Firebase authentication email password register or sign-in almost the same with the previous Login. The difference just a Firebase method, this time using createUserWithEmailAndPassword. Open and edit components/Register.js then add these imports to the required elements and Firebase auth.

import React, { useState } from 'react';
import { StyleSheet, ActivityIndicator, View, Text, Alert } from 'react-native';
import { Button, Input, Icon } from 'react-native-elements';
import auth from '@react-native-firebase/auth';

Add these useState constant variables at the first line of the Register function body.

const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [showLoading, setShowLoading] = useState(false);

Add the asynchronous function to register to the Firebase auth with email and password.

const register = async() => {
    setShowLoading(true);
    try {
        const doRegister = await auth().createUserWithEmailAndPassword(email, password);
        setShowLoading(false);
        if(doRegister.user) {
            navigation.navigate('Home');
        }
    } catch (e) {
        setShowLoading(false);
        Alert.alert(
            e.message
        );
    }
};

Modify the views that implement the Register Form using a combination of react-native and react-native-elements elements.

return (
    <View style={styles.container}>
        <View style={styles.formContainer}>
            <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
                <Text style={{ fontSize: 28, height: 50 }}>Register Here!</Text>
            </View>
            <View style={styles.subContainer}>
                <Input
                    style={styles.textInput}
                    placeholder='Your Email'
                    leftIcon={
                        <Icon
                        name='mail'
                        size={24}
                        />
                    }
                    value={email}
                    onChangeText={setEmail}
                />
            </View>
            <View style={styles.subContainer}>
                <Input
                    style={styles.textInput}
                    placeholder='Your Password'
                    leftIcon={
                        <Icon
                        name='lock'
                        size={24}
                        />
                    }
                    secureTextEntry={true}
                    value={password}
                    onChangeText={setPassword}
                />
            </View>
            <View style={styles.subContainer}>
                <Button
                    style={styles.textInput}
                    icon={
                        <Icon
                            name="check-circle"
                            size={15}
                            color="white"
                        />
                    }
                    title="Register"
                    onPress={() => register()} />
            </View>
            <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
                <Text>Already a user?</Text>
            </View>
            <View style={styles.subContainer}>
                <Button
                    style={styles.textInput}
                    icon={
                        <Icon
                            name="input"
                            size={15}
                            color="white"
                        />
                    }
                    title="Login"
                    onPress={() => {
                        navigation.navigate('Login');
                    }} />
            </View>
            {showLoading &&
                <View style={styles.activity}>
                    <ActivityIndicator size="large" color="#0000ff" />
                </View>
            }
        </View>
    </View>
);

Finally, add these codes of styles after the navigationOptions.

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    formContainer: {
        height: 400,
        padding: 20
    },
    subContainer: {
        marginBottom: 20,
        padding: 5,
    },
    activity: {
        position: 'absolute',
        left: 0,
        right: 0,
        top: 0,
        bottom: 0,
        alignItems: 'center',
        justifyContent: 'center'
    },
    textInput: {
        fontSize: 18,
        margin: 5,
        width: 200
    },
})
Step #7: Implementing Firebase Email Reset Password

The reset password screen just required one email input text and reset button. Also, a button to navigate back the previous screen. Open and edit components/Reset.js then add/replace these imports of the required elements and Firebase auth.

import React, { useState } from 'react';
import { StyleSheet, ActivityIndicator, View, Text, Alert } from 'react-native';
import { Button, Input, Icon } from 'react-native-elements';
import auth from '@react-native-firebase/auth';

Add these required useState constant variables at the first line of the Reset function body.

const [email, setEmail] = useState('');
const [showLoading, setShowLoading] = useState(false);

Add this function to send an email for a reset password to Firebase authentication. The Firebase will send the reset link email to the email that sends in this function.

const reset = async() => {
    setShowLoading(true);
    try {
        await auth().sendPasswordResetEmail(email);
        setShowLoading(false);
    } catch (e) {
        setShowLoading(false);
        Alert.alert(
            e.message
        );
    }
};

Add this implementation of view for Reset password form by modifying the existing return.

return (
    <View style={styles.container}>
        <View style={styles.formContainer}>
            <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center'}}>
                <Text style={{ fontSize: 28, height: 50  }}>Reset Password!</Text>
            </View>
            <View style={styles.subContainer}>
                <Input
                    style={styles.textInput}
                    placeholder='Your Email'
                    leftIcon={
                        <Icon
                        name='mail'
                        size={24}
                        />
                    }
                    value={email}
                    onChangeText={setEmail}
                />
            </View>
            <View style={styles.subContainer}>
                <Button
                    style={styles.textInput}
                    icon={
                        <Icon
                            name="input"
                            size={15}
                            color="white"
                        />
                    }
                    title="Reset"
                    onPress={() => reset()} />
            </View>
            <View style={styles.subContainer}>
                <Button
                    style={styles.textInput}
                    icon={
                        <Icon
                            name="check-circle"
                            size={15}
                            color="white"
                        />
                    }
                    title="Back to Login"
                    onPress={() => {
                        navigation.navigate('Login');
                    }} />
            </View>
            {showLoading &&
                <View style={styles.activity}>
                    <ActivityIndicator size="large" color="#0000ff" />
                </View>
            }
        </View>
    </View>
);

Finally, add these styles for this Reset Form after the navigationOptions.

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    formContainer: {
        height: 400,
        padding: 20
    },
    subContainer: {
        marginBottom: 20,
        padding: 5,
    },
    activity: {
        position: 'absolute',
        left: 0,
        right: 0,
        top: 0,
        bottom: 0,
        alignItems: 'center',
        justifyContent: 'center'
    },
    textInput: {
        fontSize: 18,
        margin: 5,
        width: 200
    },
})
Step #8: Implementing a Secure Home Screen

The Home screen is the initial screen that comes first when this React Native app started. So, there will be a function to check the authenticated user. If it exists then this screen will display the user email. If not exists, it will be redirected to the Login screen. Open and edit components/Home.js then add/replace these imports of required elements and Firebase auth.

import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';
import { Button, Icon } from 'react-native-elements';
import auth from '@react-native-firebase/auth';

Add these required useState constant variables inside the first line of the Home function body.

const [initializing, setInitializing] = useState(true);
const [user, setUser] = useState();

Add a function that sets the user value if the user authenticated.

function onAuthStateChanged(user) {
    setUser(user);
    if (initializing) setInitializing(false);
}

Add the useEffect function check the authenticated user every time the screen loaded.

useEffect(() => {
    const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
    return subscriber; // unsubscribe on unmount
}, []);

Add a condition that returns null user if initializing is true.

if (initializing) return null;

Add a condition that redirects to the Login page if there's no user exists or loaded.

if (!user) {
    return navigation.navigate('Login');
}

Modify the view to implementing the user email on this screen.

return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Welcome {user.email}</Text>
    </View>
);

Finally, modify the navigationOptions to add the logout button that fires the logout method of Firebase auth.

Home.navigationOptions = ({ navigation }) => ({
    title: 'Home',
    headerRight: () => <Button
            buttonStyle={{ padding: 0, marginRight: 20, backgroundColor: 'transparent' }}
            icon={
                <Icon
                    name="cancel"
                    size={28}
                    color="white"
                />
            }
            onPress={() => {auth().signOut()}} />,
});
Step #9: Run and Test React Native Firebase Email Login App

This time to run and test the React Native Firebase Email login app in the iOS simulator and Android device. To run this app to the iOS device, you need an XCode Signing Development Team. For iOS, type this command.

react-native run-ios

When the new terminal windows open, type this command immediately.

cd ~/Apps/RNEmailAuth && yarn start

To run in an Android device, make sure the Android phone connected to the computer and available by this command.

adb devices

Next, run to the android device by type this command.

react-native run-android

When the new terminal windows open, type this command immediately.

cd ~/Apps/RNEmailAuth && yarn start

And here they are the fully working React Native Firebase Authentication Email/Password.

You also can check the registered email in the Firebase console like this.

And the received password reset email link should be similar to this.

That it's, the React Native Tutorial: Firebase Email Login Example. You can get the full source code in our GitHub.

Thanks!

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

What’s new in HTML6

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Hire React Js Developer from Expert React JS Development Company

Hire React Js Developer from Expert React JS Development Company

Are you looking to [hire React JS developer](https://www.mobiwebtech.com/react-js-development-company/ "hire React JS developer") from a prestigious and reliable React JS development company? Visit at Mobiweb Technologies here we have a big team...

Are you looking to hire React JS developer from a prestigious and reliable React JS development company? Visit at Mobiweb Technologies here we have a big team of expert React JS developers, you can hire them on an hourly, weekly or monthly basis for the successful completion of your dream project.

How to Share Code Between React and React Native

How to Share Code Between React and React Native

Learn how to share code between React and React Native to avoid duplicating logic. Sharing Code Between React and React-Native: What Not to Share. This question of sharing code between React and React Native, in fact, one of the hot topics among React and React native developers all over the world. React and React-Native allow a learn once write anywhere paradigm. This is great, because one tech team can build both your web app and native mobile experience. The problem is developers hate writing things twice. There have been a couple of efforts to build a unifying technology to write an application once and have it work on both web and native.

How to Share Code Between React and React Native

Sharing Code Between React and React-Native: What Not to Share - Ben Ellerby

React and React-Native allow a learn once write anywhere paradigm. This is great, because one tech team can build both your web app and native mobile experience. The problem is developers hate writing things twice. There have been a couple of efforts to build a unifying technology to write an application once and have it work on both web and native. Yet this is not always the best approach. There is value in only sharing your business and state logic; keeping your render code separate.

In this talk I will give real examples from my work with MADE.COM, migrating their web and mobile application to React and React-Native with code sharing as a primary objective.

How to Share Code Between React and React Native

Learn how to share code between React and React Native to avoid duplicating logic

Sharing Code Between React and React Native

React and React-Native allow a learn once write anywhere paradigm. This is great, because one tech team can build both your web app and native mobile experience. The problem is developers hate writing things twice. There have been a couple of efforts to build a unifying technology to write an application once and have it work on both web and native. Yet this is not always the best approach. There is value in only sharing your business and state logic; keeping your render code separate.

React Native Tutorial - Build Android and iOS App from Scratch

React Native Tutorial - Build Android and iOS App from Scratch

React Native Tutorial - Build Android and iOS App from Scratch. Getting started tutorial on building an Android and iOS app from scratch using React Native. React Native is a modern Javascript framework backed by Facebook that use to make Mobile Apps (Android/iOS) development easier for Javascript developer. In other words, React Native is React.js mobile apps development version.

A comprehensive step by step tutorial on building Android and iOS app from scratch using React Native

A comprehensive getting started tutorial on building an Android and iOS app from scratch using React Native. React Native is a modern Javascript framework backed by Facebook that use to make Mobile Apps (Android/iOS) development easier for Javascript developer. In other words, React Native is React.js mobile apps development version. For more information about React Native definition, features, etc, you can find in their official documentation.

Shortcut to the steps:

  • Install React App Creator and Create A React Native App
  • Add Navigation Header and Home Screen
  • Load World Cup 2018 Data from API
  • Display List of World Cup Matchdays
  • Display World Cup 2018 Matchdays Details
  • Run the React Native World Cup 2018 App

In this React Native tutorial, we are creating an app that listing the World Cup 2018 matches using the free open public domain football data for the world cups in the JSON format.

The following tools, frameworks, and modules are required for this tutorial:

  • React Native
  • Node.js (NPM or Yarn)
  • Worldcup JSON data
  • Android Studio or SDK for Android
  • XCode for iOS
  • Terminal (OSX/Linux) or Command Line (Windows)
  • Text Editor or IDE (We are using Atom)

Before start to the main steps, make sure that you have installed Node.js and can run npm in the terminal or command line. To check existing or installed Node.js environment open the terminal/command line then type this command.

node -v
v8.11.1
npm -v
6.1.0
yarn -v
1.7.0

That's the Node and NPM or YARN version that we are using. In this tutorial, we will use Yarn commonly.

Install React App Creator and Create A React Native App

The Create React Native App is a tool for creating a React Native App. To install it, type this command in your App projects folder.

sudo npm install -g create-react-native-app

Then create a React Native App using this command.

create-react-native-app reactWorldCupApp

That command will create a React Native app then install all required modules. The app or project folder will contain these folders and files.

Next, go to the newly created React App folder.

cd reactWorldCupApp

This React Native App is running via Expo app, before running on your Android or iOS device, make sure you have to install the Expo App to Android or Expo Client to iOS. Of course, that app is available in the App Store. So, we assume that you have installed the Expo App in your device then type this command to run the app.

npm start

or

yarn start

You will see this barcode and instruction in the terminal or command line.

To open the app in the Android device, open the Expo App first then tap on Scan QR Code button. Scan the barcode in the terminal or command line then you will see the React Native Android App like this after waiting for minutes the build process.

For iOS Device, press s from the keyboard to send React Native App URL to your Email or SMS. Enter your phone number or Email address (We use an email address) then press Enter. You will get this email to your mailbox.

Choose open in Expo URL then open in your browser, that will be redirected to Expo App. In Expo App welcome screen, shake your phone to open the React Native App. Now, you will see this screen in your iOS device.

This step for development purpose, we will show you how to build for production at the end of this article.

Add Navigation Header and Home Screen

Above generated React Native App just show blank app with plain text. Now, we will show you how to add the Navigation Header and Home Screen for your app. So, it will look like the Native App. In the terminal or command line type this command to install React Navigation (react-navigation) module.

yarn add react-navigation

Next, create a folder for components and React Native components files in the root of the app folder.

mkdir components
touch components/HomeScreen.js
touch components/DetailsScreen.js

Open and edit components/HomeScreen.js then add this React Native codes.

import React, { Component } from 'react';
import { Button, View, Text } from 'react-native';

class HomeScreen extends Component {
  static navigationOptions = {
    title: 'Home',
  };
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Home Screen</Text>
        <Button
          title="Go to Details"
          onPress={() => this.props.navigation.navigate('Details')}
        />
      </View>
    );
  }
}

export default HomeScreen;

Open and edit components/DetailsScreen.js then add this React Native codes.

import React, { Component } from 'react';
import { Button, View, Text } from 'react-native';

class DetailsScreen extends Component {
  static navigationOptions = {
    title: 'Details',
  };
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Details Screen</Text>
        <Button
          title="Go to Details... again"
          onPress={() => this.props.navigation.push('Details')}
        />
        <Button
          title="Go to Home"
          onPress={() => this.props.navigation.navigate('Home')}
        />
        <Button
          title="Go back"
          onPress={() => this.props.navigation.goBack()}
        />
      </View>
    );
  }
}

export default DetailsScreen;

Next, open and edit App.js then add replace all codes with this.

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { createStackNavigator } from 'react-navigation';
import HomeScreen from './components/HomeScreen';
import DetailsScreen from './components/DetailsScreen';

const RootStack = createStackNavigator(
  {
    Home: HomeScreen,
    Details: DetailsScreen,
  },
  {
    initialRouteName: 'Home',
    navigationOptions: {
      headerStyle: {
        backgroundColor: '#f4511e',
      },
      headerTintColor: '#fff',
      headerTitleStyle: {
        fontWeight: 'bold',
      },
    },
  },
);

export default class App extends React.Component {
  render() {
    return <RootStack />;
  }
}

When the files are saved, the Expo app will refresh the React Native App automatically. Now, the app will look like this.

Load World Cup 2018 Data from API

To load World Cup 2018 data from API, open and edit components/HomeScreen.js then add constructor function before rendering function.

constructor(props){
  super(props);
  this.state ={ isLoading: true}
}

Add function for load API JSON data which the JSON response set to the dataSource.

componentDidMount(){
  return fetch('https://raw.githubusercontent.com/openfootball/world-cup.json/master/2018/worldcup.json')
    .then((response) => response.json())
    .then((responseJson) => {
      // console.log(responseJson);
      this.setState({
        isLoading: false,
        dataSource: responseJson.rounds,
      }, function(){

      });

    })
    .catch((error) =>{
      console.error(error);
    });
}

The response from API holds by dataSource variable that will use in the view in the next step.

Display List of World Cup Matchdays

We will use the List and ListItem component of React Native Elements (react-native-elements) module. First, install react-native-elements using this command.

yarn add react-native-elements

Open and edit again components/HomeScreen.js then replace all imports with these imports of React, Component (react), StyleSheet, ScrollView, ActivityIndicator, Text, View (react-native), List, and ListItem (react-native-elements).

import React, { Component } from 'react';
import { StyleSheet, ScrollView, ActivityIndicator, Text, View  } from 'react-native';
import { List, ListItem } from 'react-native-elements';

Next, replace all render function with this React Native rendered template which the ActivityIndicator load only if the state status is loading. The list that gets from the data source displaying to the ListItem after mapping the array of the data source.

render() {
  if(this.state.isLoading){
    return(
      <View style={styles.activity}>
        <ActivityIndicator/>
      </View>
    )
  }

  return(
    <ScrollView style={styles.container}>
      <List>
        {
          this.state.dataSource.map((item, i) => (
            <ListItem
              key={i}
              title={item.name}
              leftIcon={{name: 'soccer-ball-o', type: 'font-awesome'}}
              onPress={() => {
                this.props.navigation.navigate('Details', {
                  matches: `${JSON.stringify(item.matches)}`,
                });
              }}
            />
          ))
        }
      </List>
    </ScrollView>
  );
}

Add style const before the export code.

const styles = StyleSheet.create({
  container: {
   flex: 1,
   paddingBottom: 22
  },
  item: {
    padding: 10,
    fontSize: 18,
    height: 44,
  },
  activity: {
    flex: 1,
    padding: 20,
  }
})
Display World Cup 2018 Matchdays Details

We will display World Cup 2018 Matchdays Details in the DetailsScreen. Open and edit components/DetailsScreen.js then replace all imports with this.

import React, { Component } from 'react';
import { StyleSheet, ScrollView, View } from 'react-native';
import { List, ListItem, Text, Card } from 'react-native-elements';

Next, replace all render function with these lines codes.

render() {
  const { navigation } = this.props;
  const matches = JSON.parse(navigation.getParam('matches', 'No matches found'));
  console.log(matches);

  return (
    <ScrollView>
      <Card style={styles.container}>
        {
          matches.map((item, key) => (
            <View key={key} style={styles.subContainer}>
              if(item.group) {
                <View>
                  <Text h3>{item.group}</Text>
                </View>
              }
              <View>
                <Text h3>{item.team1.name} vs {item.team2.name}</Text>
              </View>
              <View>
                <Text h5>{item.date}</Text>
              </View>
              <View>
                <Text h4>{item.score1} - {item.score2}</Text>
              </View>
              if(item.goals1.length > 0) {
                item.goals1.map((item2, key2) => (
                  <View key={key2}>
                    <Text h4>{item2.name} ({item2.minute})</Text>
                  </View>
                ))
              }
              if(item.goals2.length > 0) {
                item.goals2.map((item3, key3) => (
                  <View key={key3}>
                    <Text h5>{item3.name} ({item3.minute})</Text>
                  </View>
                ))
              }
            </View>
          ))
        }
      </Card>
    </ScrollView>
  );
}

Add StyleSheet const before the export code.

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20
  },
  subContainer: {
    flex: 1,
    paddingBottom: 20,
    borderBottomWidth: 2,
    borderBottomColor: '#CCCCCC',
  }
})
Run the React Native World Cup 2018 App

To run the application in Expo App, you can find in step 1 of this article. If there's no error found, you will see the result like this.


Next, to run or build as the Native App, type this command to install React Native CLI first.

sudo npm install -g react-native-cli

Next, eject the project from the Create React Native App by type this command.

npm run eject

You will get questions like below, make it the same with the one that we choose.

? How would you like to eject from create-react-native-app? React Native: I'd like a regular React Native project.
We have a couple of questions to ask you about how you'd like to name your app:
? What should your app appear as on a user's home screen? React World Cup
? What should your Android Studio and Xcode projects be called? ReactWorldCupApp

Next, to run the Native iOS or Android App in the Simulator, type this command.

react-native run-ios
react-native run-android

That it's for now. Any suggestions are open for next React Native tutorial. You can find the full working source code in our GitHub.