How to add pagination to a React-Native flatlist

This tutorial will explain how to add pagination to your flatlist while scrolling, so 10 more items get added to the flatlist the more you scroll.

The first thing we need to do as always is create a new React-Native project, use the command below.

react-native init paginationflatlist

After we have created the project we need to open this in your favourite code editor, mine is VS code.

The firs thing we need to do is open the “App.js” file and change the “App” class to be the below.

class App extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                loading: true,
                randomUserData: [],
                loadingExtraData: false,
                page: 1
            }
        }
        render() {
                return ( <View> </View>
                     )
                       
        }
}

The class includes a constructor that will contain a state object.

The state object contains a “loading” key which will be the value of an activity indicator that loads on load of the component. A “randomUserData” array which will contain the flatlist data, and a “loadingExtraData” boolean that will be the value of another activity indicator for when we load extra data. In addition, we have a state value for the page of the flatlist so we can monitor whether we are only loading the first 10 results or the next 10.

After you have copied this we need to import the “FlatList” and “TouchableOpacity” components from React-Native so now our import will look like the below.

import React from 'react';import {SafeAreaView,StyleSheet,ScrollView,View,Text,StatusBar,FlatList,TouchableOpacity} from 'react-native';

We now need to create a method named “LoadRandomData” and use fetch to retrieve data from our random data api. The url we will be retrieving from is “https://randomuser.me/api/?results=10”, so the max number of results we can get at a time is 10.

fetch('https://randomuser.me/api/?results=10')

We will now use a promise to access the response and then convert the response to json using “response.json”

fetch(`https://randomuser.me/api/?results=10&page=${this.state.page}`).then(response=>response.json())

We then will access this json data through another “then” and set our state value “randomUserData” depending on what the “page” value is, because if it is one then we only want to load the first page retrieved from the API, however, if “page” is greater than 1 then we want to concatenate the current state array with the array of the latest results retrieved from the API, so our data from page 1 will concatenate with page 2, giving it the pagination functionality, the 3 dots “…” are also known as the spread operator.

fetch(`https://randomuser.me/api/?results=10&page=${this.state.page}`).then(response => response.json()).then(responseJson => {
    this.setState({
        randomUserData: this.state.page === 1 ? responseJson.results : [...this.state.randomUserData, ...responseJson.results]
    })
})

We will also add a “catch” so we can see any errors that are returned in the console.

LoadRandomData = () => {
    fetch(`https://randomuser.me/api/?results=10&page=${this.state.page}`).then(response => response.json()).then(responseJson => {
        this.setState({
            randomUserData: this.state.page === 1 ? responseJson.results : [...this.state.randomUserData, ...responseJson.results]
        })
    }).catch(error => {
        console.log('Error selecting random data: ' + error)
    })
}

The next thing we need to do is add a “FlatList” component and set its data property equal to “this.state.randomUserData”. Also we need to run our “LoadRandomData” on the “componentDidMount” lifecycle method so the data from the API shows on the flatlist on the load of the component.

<View style={{ marginTop: 50 }}><FlatListdata={this.state.randomUserData}style={{ width: 350, height: 800 }}/></View>

So now our “flatlist” has a container and style properties too.

Below is how our “componentDidMount” lifecycle method currently looks.

componentDidMount() {this.LoadRandomData()}

Our next step is to determine how we want our data on the “Flatlist” to show using the in built method “renderItem”.

Make a method named “renderCustomItem” which has 2 parameters and are destructured, the parameter names must be “item” and “index”.

We will be returning the gender, name and image from the API. So copy the code below to do this within the “renderCustomItem” method.

renderCustomItem = ({
    item,
    index
}) => {
    return ( < View style = {
            {
                justifyContent: 'center',
                alignItems: 'center'
            }
        } > < Text > {
            item.gender
        } < /Text><Text>{item.name["first"]} {item.name["last"]}</Text > < Image source = {
            {
                uri: item.picture["medium"]
            }
        }
        style = {
            {
                width: 200,
                height: 200
            }
        }
        /></View > )
}

“name” is a key of another object hence why we have to traverse it the way we do. I should have said this earlier but you now must import the “Image” component from “react-native” so now our “import” statement from react-native looks like the below.

import {SafeAreaView,StyleSheet,ScrollView,View,Text,StatusBar,FlatList,TouchableOpacity,Image} from 'react-native';

We set the “Source” property equal to the “medium” object key of “picture” from the API. The “uri” is there to represent the url as a resource identifier.

So now that we have created the custom item method we set the in built method “renderItem” to

renderItem={this.renderCustomItem}

After you have done all of this run the command below for the iOS simulator.

react-native run-ios

You should see something like the below.

We now need to create a method that will contain the keyExtractor. A key extractor tells the flat list to use a specified id/key instead of the default key property.

We will set ours to the users email address, so create a method called “keyExtractor” with 2 parameters “item” and “index” and set the value to “item.email” like below.

keyExtractor = (item,index) => item.email;

So now our flat list looks like the below.

<FlatListdata = {
    this.state.randomUserData
}
renderItem = {
    this.renderCustomItem
}
style = {
    {
        width: 350,
        height: 800
    }
}
keyExtractor = {
    this.keyExtractor
}
/>

We now need to create a method that will handle the loading of the next 10 records on the flatlist we will call this method “LoadMoreRandomData”.

All we need to do in this method is increment the state value of “page” by 1, and use the callback of set state to run the “LoadRandomData” method. We increment the page value because in our fetch request we set a query parameter called “page” equal to the state value “page” so by default the state value “page” is 1, so the first page of the first 10 results is loaded, then when we get to the bottom of the flatlist the next 10 results are loaded.(I will explain how react-native knows you are at the bottom in a second)

“onEndChanged” is a built in method on the flatlist and for our project that runs the “LoadMoreRandomData” method, increments the “page” state value by 1 so it would be 2, and retrieves the second page of the API data because the query param “page” in the “fetch” request url is set to the “page” state value, then in the “LoadRandomData” it then does a check if the state value “page” is 1 then just retrieve the first set of results, else if it is not 1 then concatenate the new set of retrieved data with the original set of data.

After adding those changes the flatlist will look the below.

LoadMoreRandomData = () =>{this.setState({page:this.state.page+1},()=>this.LoadRandomData())}

For react-native to know you are at the bottom or near the bottom of the flatlist there are 2 methods to know about, these are “onEndReachedThreshold” and “onEndReached”.

OnEndReachedThreshold is a numeric value which runs the “onEndReached” method depending on how far from the end the bottom edge of the list has to be from the end of the content to run the method “onEndReached”. If you were to set the value to 0.5 “onEndReached” will run when the content is half way visible length of the list, however, for now lets just set it to 0 so we have to be at the bottom of the list to reload the data.

So now our flatlist looks like the below.

<FlatListdata = {
    this.state.randomUserData
}
renderItem = {
    this.renderCustomItem
}
style = {
    {
        width: 350,
        height: 800
    }
}
keyExtractor = {
    this.keyExtractor
}
onEndReachedThreshold = {
    0
}
onEndReached = {
    this.LoadMoreRandomData
}
/>

If you run the simulator again you should a working flatlist and when you scroll down to the bottom another 10 results from the API should appear.

We could add more customization to this including a loading indicator and footer component, however, I just wanted to keep it simple for this tutorial.

Hopefully you learned something from this tutorial, if I can improve on anything please let me know and I will try to incorporate those changes in my next tutorial.

How to add sound to a react-native app

Hi everyone, it has been a loooong time since I have written an article and thought I would do another today regarding adding sound to a react native app. Let’s go!

Firstly, the documentation for this can be found here — https://www.npmjs.com/package/react-native-sound and has a lot of great stuff in it, but if you like the format of Medium feel free to stick around!

I will be using React-Native 0.60 version or greater so you will most likely need to do a pod install but I will talk about that later.

The first thing you will want to do is to open your command prompt/terminal and create a react-native project, to do this enter the below.

Playing from local file

react-native init mysoundproject

After you have done this a project folder will be created, open this project in your favoured text editor, open the terminal within your text editor, to open this in vs code on a mac you will need to press “ctrl” and “`” at the same time.

Now enter the command

npm install react-native-sound --save

This will install the react-native-sound which is a fantastic package which allows you to play sounds locally from a project or from a url as well as a myriad of other features!

After that has installed you will need to link the dependencies, if you are using React-Native 0.60 you can run the below command

cd ios && pod install

This will change to the directory “ios” and begin to link the dependencies.

However, if you are on a previous React-Native version you can use the below command.

react-native link react-native-sound

After you have done run the simulator in either Android or iOS using either of the below commands

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

This first run may take a while so be patient 🙂

I will show examples of both an audio file stored locally and a file from a remote url.

Firstly, remove the class or const “App” variable and replace it was the below. We are just creating a couple touchable areas on the screen to run our methods.

class App extends React.Component {
    render() {
        return ( <
            View >
            <
            View style = {
                {
                    marginTop: 100
                }
            } >
            <
            TouchableOpacity style = {
                {
                    backgroundColor: 'grey',
                    justifyContent: 'center'
                }
            } >
            <
            Text style = {
                {
                    textAlign: 'center',
                    fontSize: 20,
                    color: 'white',
                    padding: 10
                }
            } > Play sound from local file < /Text> <
            /TouchableOpacity> <
            /View> <
            View style = {
                {
                    marginTop: 100
                }
            } >
            <
            TouchableOpacity style = {
                {
                    backgroundColor: 'grey',
                    justifyContent: 'center'
                }
            } >
            <
            Text style = {
                {
                    textAlign: 'center',
                    fontSize: 20,
                    color: 'white',
                    padding: 10
                }
            } > Play sound from remote url < /Text> <
            /TouchableOpacity> <
            /View> <
            /View>
        )
    }
}

Your app should now look like the below

The next step is to make sure you have a sound file to use I will be using a sound file called “da.mp3” for this tutorial as it is a voice recording in Russian I made. For playing a local file on Android you will need to locate the below directory within your Android folder in the react-native project.

android/app/src/main/res

NOTE: The sound files you want to play MUST be lowercase and underscored if necessary.

Inside of the res folder create another folder called “raw”, this will contain your local sound file, I have now copied my sound file to that location.

if you want to play a sound file from your iOS simulator you will need to open your xcworkspace file in xcode (if you are using react-native 0.60 or greater) else open your xcodeproj file in xcode instead.

Once you have done that right click on your project name on the left hand side and click “Add files to yourprojectname”

Now look for your sound file on your hard-drive, be sure to tick the box labelled “Copy items if needed” and click “Add”. You will now see the sound file in your project.

We will now import the package in our App.js file using the below.

import Sound from 'react-native-sound';

We will then create a method called “PlayLocalSoundFile” and set the sound category to playback as we want to play a sound (this creates an audio session between the app and operating system so the device knows what type of audio action will happen in this method)

PlayLocalSoundFile = () =>{Sound.setCategory('Playback');}

Afterwards we will need to load our sound (remember to change the sound file name to whatever you named yours) from the main app bundle and pass in an error callback to check for any errors, inside of this variable we play the sound too using the “.play” method, and if the sound successfully plays then a console log message is added as well as setting the volume of the sound, where 0.0 is the lowest and 1 is the highest. In addition, we also release the resources.

var mySound = new Sound('da.mp3',Sound.MAIN_BUNDLE,(error)=>{if(error){console.log('Error loading sound: ' + error);return;}else{mySound.play((success)=>{if(success){console.log('Sound playing')}else{console.log('Issue playing file');}})}});mySound.setVolume(0.9);
mySound.release();

We will now run this method on press of the first touchable opacity, so copy the below code into the touchable opacity component.

onPress={()=>this.PlayLocalSoundFile()}

It should now look like the below.

<TouchableOpacity style={{backgroundColor:'grey',justifyContent:'center'}} onPress={()=>this.PlayLocalSoundFile()} ><Text style={{textAlign:'center',fontSize:20,color:'white',padding:10}}>Play sound from local file</Text></TouchableOpacity>

Playing sound from remote URL

Playing sound from a remote url will be the exact same process apart from a few tweaks, so go ahead and create method named “PlayRemoteURLSoundFile”. This will contain our code to play the remote url sound.

Now set your category to playback like the below as again we want to play a sound not record.

PlayRemoteURLSoundFile = () =>{Sound.setCategory('Playback');}

We now create a variable that will be equal to a new Sound instance and the first parameter will be the url of the sound that you want to play, I have found a random sound from soundjay.com — https://www.soundjay.com/ambient/sounds/boarding-accouncement-1.mp3

Since we are not playing a sound file from the main bundle of the app we do not need to pass MAIN_BUNDLE, we can instead pass in null, and the third param will be an error callback. So now our method will be the same as the previous one for the local sound file. Our remote url method will look like the below.

PlayRemoteURLSoundFile = () =>{Sound.setCategory('Playback');var myRemoteSound = new Sound('https://www.soundjay.com/ambient/sounds/boarding-accouncement-1.mp3',null,(error)=>{if(error){console.log(error);return;}else{myRemoteSound.play((success)=>{if(success){console.log('Sound playing')}else{console.log('Issue playing file');}})}});myRemoteSound.setVolume(0.9);myRemoteSound.release();}

I have tested both sound files on both platforms and each method runs successfully and plays the file.

Note: When you test on an Android simulator if you get the error

“Could not initialize class org.codehaus.groovy.vmplugin.v7.Java7”

Try cleaning and rebuilding the project in Android studio as that occured when I was testing and that seemed to fix the issue.

Example Use case

When I have been developing apps in my spare time I have at times wanted to play a sound file when clicking on an icon on a row within the flat list.

When doing this I would have a column in the database table named “SoundFileName” which would be equal to the name of the sound file you want to play. So when you pull back your data for your flat list you can pull back the sound file name, place it in a method parameter and put this parameter in the first partner for the “new Sound” variable. That way when you click on a row it will look for that sound file name to play that you have stored locally or on a remote url somewhere. That is just my 2 cents, if anyone else has a better way of playing sound files when clicking on a flat list item feel free to respond to this article!

Below are a few code examples of how I have incorporated this.

Thank you very much for reading this article it would be much appreciated if you could clap the article and share with others ☺

Have a good say and stay safe

How to add font-awesome 5 icons to your React-Native project

It is great weather time in the UK at the moment so I thought i would do another tutorial, this time i will be showing you how to incorporate font-awesome icons into your React-Native project. Here we go!

So first thing is to open your terminal or command prompt and navigate to the folder in which your project to be, then enter

react-native init myfontawesomeproject

Once you have created this project there are various packages you will need install to be able to font awesome icons, enter the below on your terminal within your project to install those packages.

npm i --save react-native-svg
npm i --save @fortawesome/fontawesome-svg-core
npm i --save @fortawesome/free-solid-svg-icons
npm i --save @fortawesome/react-native-fontawesome

The ‘fontawesome-svg-core’ package mixes JavaScript with SVG

Once you have ran all of these commands we need to complete the setup of installing these pod packages on iOS so enter the below

cd ios && pod install

If you wish to company/brand icons such as Amazon or Apple’s in your react-native app then you can install the below ( I will be showing an example of this in my tutorial later so if you want to follow my tutorial exactly you should install this package too 🙂 )

npm i --save @fortawesome/free-brands-svg-icons

In addition, if you want include the regular icons of font awesome you can install the below (this gives you access to things like address-card, acorn, angry, apple-alt and badge-sheriff)

npm i --save @fortawesome/free-regular-svg-icons

Furthermore, if you are subscribed to the pro version of font-awesome (which you are a very lucky person if you are!) install the below packages

npm i --save @fortawesome/pro-solid-svg-icons
npm i --save @fortawesome/pro-regular-svg-icons
npm i --save @fortawesome/pro-light-svg-icons

If you install any of those additional packages remember to run the below again to link the iOS dependencies.

cd ios && pod install

If you have already ran your react-native project and have the simulator open please close the simulator and terminal as sometimes react-native will not work if you have just installed dependencies and new functionality such as fonts and requires a complete restart.

Now when you have restarted the application removed whatever react-native presets your “app” const variable to be and replace it with the below

class App extends React.Component{render(){return(<View style={{marginTop:100}}><Text style={styles.centerText}>My font awesome project!</Text></View>)}}

In addition, replace “styles” stylesheet with the below

const styles = StyleSheet.create({centerText:{textAlign:'center'}});

Your app should now look incredibly amazing like the below

To use the fonts is incredibly easy thanks to the packages developed, all we need to do is import the “FontAwesomeIcon” from the “react-native-fontawesome” package in the App.js file using the code below, this will act as a container for the icon which we set as a prop within the “FontAwesomeIcon” component.

import { FontAwesomeIcon } from '@fortawesome/react-native-fontawesome';

For this tutorial i will be importing icons from the “free-solid-svg-icons” and “free-brands-svg-icons” package.

The next step is to import the icon from the relevant package.

Below are the 3 icons I will be importing from the “free-solid-svg-icons” package in the App.js file

import { faLock,faAirFreshener,faAnchor } from '@fortawesome/free-solid-svg-icons';

Below are the 3 icons I will be importing from the “free-brands-svg-icons” package in the App.js file

import {faAdobe,faApple,faMicrosoft} from '@fortawesome/free-brands-svg-icons';

Furthermore, before using these on the screen I will create a view container for the first 3 from the solid svg package and set a couple style attributes to make the icons appear nicer.

<View style={{ flexDirection: 'row', justifyContent:'space-evenly' }}></View>

I have set a “flexDirection” of row which will show the content inside horizontally instead of vertically and “justifyContent” set to “space-evenly” will space out the 3 icons with equal space in between.

<FontAwesomeIcon icon={faLock} size={40} color={"blue"} />

Above is a basic example of how to use a “FontAwesomeIcon”, see that we use the “icon” prop to refer to a font-awesome icon we imported from the “free-solid-svg-icons” package. We can also set the colour and size as well as a few more props of the icon such as style, transform and masking, however, that is out of scope for this tutorial. Think of the “size” prop as the font-size attribute used. We will now use the “FontAwesomeIcon” 2 more times so now our view container code will look like the below.

<View style={{ flexDirection: 'row', justifyContent:'space-evenly' }}><FontAwesomeIcon icon={faLock} size={40} color={"blue"} /><FontAwesomeIcon icon={faAirFreshener} size={30} color={"red"} /><FontAwesomeIcon icon={faAnchor} size={50} color={"purple"} /></View>
Output of the font-awesome code from the svg-icons package

I will now do the exact same for the “brand” package

<View style={{ flexDirection: 'row', justifyContent:'space-evenly' }}><FontAwesomeIcon icon={faAdobe} size={30} /><FontAwesomeIcon icon={faApple} size={30} /><FontAwesomeIcon icon={faMicrosoft} size={50} /></View>

If we just write that code you will see that icons show but are black, if you want to add colour to the icons just use the colour prop. I have added some colour to the brands icons below.

<View style={{ flexDirection: 'row', justifyContent:'space-evenly' }}><FontAwesomeIcon icon={faAdobe} size={30} color={'red'} /><FontAwesomeIcon icon={faApple} size={30} color={'grey'} /><FontAwesomeIcon icon={faMicrosoft} size={50} color={'#48dbfb'} /></View>

So now the app looks like the following.

And there you have it, I know this was a very basic tutorial but it was meant to be just that, as I think most people will just want to really find out how to use font-awesome in react-native and maybe not do so much customising, however, every circumstance is different.

So we just need to install the necessary packages (remember to do “pod install” too when inside the ios folder)

Restart the simulator and terminal

Import the “FontAwesomeIcon” component from “react-native-fontawesome”

Import the icon from the package it is contained

Then set any additional props you’d like

Thank you for reading, I hope you learned something from this tutorial and found it informative!

Take care!

How to send emails using NodeMailer, gmail and OAuth2

Hi there, I thought that since sending emails was one of the first features of my app I am building I thought it would be cool to do a tutorial on it!

The email will be sent from an API end point and will use OAuth2 credentials to send them, this is much better from a security point of view as don’t have to store actual email credentials but instead store and use access tokens and these can only be used for certain purposes for a short amount of time.

Since we will be sending the email from an API endpoint we will first need to create a NodeJS project with the command below in the terminal

npm init myamazingproject

You can call your project whatever you like, now after you have ran this statement you will need to open the project in your favourite code editor I always use VS Code. Now create a file in the root of the project named “server” and make sure it is a JavaScript file, we will now need to install multiple packages including express, body-parser, nodemailer and google apis. You can do this using the command below

npm install express body-parser nodemailer googleapis

This will install all 4 packages and create a package-lock.json file, this file is created whenever the node_modules folder is modified by npm.

The package nodemailer is basically a package to allow us to send emails through NodeJS.

We will now need to require all 4 packages in our server.js file so we can use them. We have created an extra variable called “OAuth2” which is equal specifically to the OAuth2 section of the google apis module.

const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const { google } = require("googleapis");
const OAuth2 = google.auth.OAuth2;

We then also create a “PORT” const which is set to either the environment variable of the system it is deployed to i.e. Heroku for example. Otherwise it is set to port 3000. This matters a lot more if you are deploying the API to an online hosting service, if you were to just set the variable to 3000 and deployed it to Heroku or Amazon then an error would occur as both those services automatically configure the environment variable port for you.

We then also need to create a variable which is an instance of the express module, i have called it “app” for my project.

const PORT = process.env.PORT || 3000;
const app = express();

One additional line of code which we will need for this tutorial is

app.use(bodyParser.json());

This uses the instance of the “express” object and also uses the variable we created to be equal to the “body-parser” module. It is basically allowing us to parse application/json data in the body of our requests.

I have also created a simple default endpoint which simply returns a message in the response.

app.get('/',function(req,res){
res.send({
message:'Default route in email tutorial project'
})
});

Furthermore, to start the server you will need to add a “start” script in the package.json file so the server.js file gets ran when the command “npm start” is ran. Below is an example of this and how the “scripts” section should look.

"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},

Finally, I have added a piece of code that runs the server and listens on a certain port which takes in the “PORT” variable as the first parameter and a callback as the second. This is always at the bottom of the file

app.listen(PORT, function (req, res) {
console.log(`Listening on port ${PORT}`);
})

Onto the meat and potatoes of this tutorial, with nodemailer you can use different services to send the email from, for this tutorial I will be using gmail, one way you can send emails in nodemailer is directly entering your email and password you want the email to be sent from.

However if you deploy this you might have issues with gmail blocking the email being sent if the server you deployed the API to is in a different location, meanwhile, for this tutorial I will be showing you how to incorporate OAuth2 access tokens into your project so all you need is your email to send from and a bunch of tokens that will be generated for you further into the tutorial.

The first thing you will need to do is a create a new project in google cloud console

Google Cloud Platform
Google Cloud Platform lets you build, deploy, and scale applications, websites, and services on the same infrastructure…console.cloud.google.com

This will enable you to create a project that will allow you to create credentials to send emails via nodemailer. Once you have gone onto this website and logged in you will see a button labelled “select a project”, click on this and then click on the button that says “new project”. The screen will look like the below.

Click “create”, the process of creating the project will then begin, after it has finished click on the notifications bell and click on the latest notification, this will take you directly to the projects dashboard.

Next step is to click on the hamburger menu on the top left, hover over “APIs & services” and then click on “credentials”.

In addition, click on the “create credentials” button and then click on “OAuth client ID”

You will now be confronted with a screen saying you need to configure your consent screen, click on this button on the top right of the page.

On the next page set the user type as “external”

In the next screen set a name for the application and then click save at the bottom, now click on the “credentials” tab on the left.

Now do the same process as before and click on Create credentials and then select the credential option labelled OAuth client ID

Now you are able to select what platform you are using the application for, select Web application. Give your application a suitable name and set the Authorised Redirect URIs to https://developers.google.com/oauthplayground

We will be using the above link to obtain our unique client and access tokens.

Now click create and after a few seconds a popup should come up showing your Client ID and Client secret (Keep these safe somewhere!)

Our next step is to navigate to a google oauth playground where we can put our client ID and secret to use. Go to this link https://developers.google.com/oauthplayground and after you have done this click on the “cog” icon on the top right of the page.

After clicking on this a menu will open, click on the checkbox labelled “Use your own OAuth credentials”, 2 new textboxes will show now within that settings menu labelled client ID and client secret, enter the credentials (client id and client secret) you have just received from the google project (the ones you should have kept safe 😉 ) into the textboxes.

Once you have done this on the left hand side of the page there should be a textbox with a placeholder of “Input your own scopes”, paste the text https://mail.google.com/ into that box and then click “Authorize APIs”.

If you are logged in to an account, the below screen should show (If you are not logged into an account log in to the one that you used to create the google cloud console project earlier)

Clicked on the word “Advanced”, then click on “go to yourprojectname” this should then show the below

Once you click “Allow” another screen should pop asking you to confirm that you are allowing the app access. Click on “Allow” again, you will then be redirected to the OAuth playground website with the “Authorization code” textbox already filled in with a value, now click on the button labelled “Exchange authorization code for tokens”.

This will create a refresh and access token (Once again keep these safe!)

We now need to go back to our project and in the “server.js” code and create a variable equal to an instance of an “OAuth2” object, create this just underneath the “app.use(bodyParser.json());” statement. The first value entered inside the parameter is the client id, the second value is the client secret and the third value is the redirect url.

const myOAuth2Client = new OAuth2(
"client ID goes here",
"client secret goes here",
"https://developers.google.com/oauthplayground"
)

We next need to use a built in method named “setCredentials” to set the value of the refresh token.

myOAuth2Client.setCredentials({
refresh_token:"refresh token from oauth playground goes here"
});

Since our access token will expire within a specific amount of time we need to write a line of code that will retrieve a new access token when it expires.

const myAccessToken = myOAuth2Client.getAccessToken()

We now need to create a transport object from the nodemailer instance that will contain the service we will use which will be gmail as well as necessary credentials. Write the below in your “server.js” file

const transport = nodemailer.createTransport({
service: "gmail",
auth: {
type: "OAuth2",
user: "your email here", //your gmail account you used to set the project up in google cloud console"
clientId: " Client ID Here",
clientSecret: "Client Secret Here",
refreshToken: "Refresh Token Here",
accessToken: myAccessToken //access token variable we defined earlier
}});

We now need to create another end point and this time it will be a “POST” request named “sendemail” it looks like the below in the server.js file.

app.post('/sendemail',function(req,res){
})

In addition, a JavaScript object will need to be created inside of this new endpoint that will contain a few options which are self-explanatory, i have called this object “mailOptions” and will look like the below. (If you want more html in your email you could create a variable prior to the “mailOptions” object and write it there, as it will look neater, the “to” value is set the email value found within the body of the request which we will be setting in postman.)

const mailOptions = {
from: 'youremailaddresshere@email.com', // sender
to: req.body.email, // receiver
subject: 'My tutorial brought me here', // Subject
html: '<p>You have received this email using nodemailer, you are welcome ;)</p>'// html body
}

To actually send an email we will need to use the “transport” variable that we created earlier and use the sendMail method of it and pass in the “mailOptions” object as the first parameter, the second parameter will be a callback function that either returns a successful result or an error. We will do basic error checking and if there is no error when we test this bad boy in postman we will send a legitimate response saying “email sent”.

app.post('/sendemail',function(req,res){
const mailOptions = {
from: 'youremailaddresshere@email.com', // sender
to: req.body.email, // receiver
subject: 'My tutorial brought me here', // Subject
html: '<p>You have received this email using nodemailer, you are welcome ;)</p>'// html body
}
transport.sendMail(mailOptions,function(err,result){
if(err){
res.send({
message:err
})
}else{
transport.close();
res.send({
message:'Email has been sent: check your inbox!'
})
}
})
})

Postman is a really great tool for testing local or deployed systems request and response status’s. You can download it from the link below.

Download Postman App
Be the first to experience new Postman features! Can’t wait to see what Postman has in store for you? Be the first to…www.postman.com

Run your server using the command “npm start” in the terminal of your chosen code editor. Now open Postman and make sure the method is set to “POST”, the text is set to “raw” and “JSON” is chosen in the data type drop down, finally, in the body tab ensure the email key and value are in between double quotes within curly brackets like below, set the email value equal to the email address you want to send to!

Then click send (which is to the right of the url) and watch your email you set up get sent to your inbox 😉

There you have it, a very simple message sent. However, you can get more complex with nodemailer in terms of multiple recipients, more complicated html and even bulk mailing!

I hope you enjoyed this article and remember to give a clap or share if you learnt something. Anything I can do to be better or improve this article feel free to tell me.

Stay safe!

How To Add Custom Fonts to Your React-Native Project

When I am beginning to plan side projects, one of the first aspects I like to think about is the fonts I want to use for the project.

Thinking of this, I realised in the past I’ve had some issues when integrating custom fonts into my React-Native project, so I thought it’d be a cool idea to make a tutorial on how to do this along with plenty of screenshots along the way. Let’s do this.

“The Day Before the Exam” (1895) by Leonid Osipovich Pasternak

The first step you’ll want to take is to create a React-Native project in your chosen folder destination with the below command.

react-native init MyProject

Secondly, you will want to go and choose a font to use in your app. I always use Google fonts for this.

What you’ll want to do is look for a font you like, then click the plus button to the right of it. This means you’ve now selected the font. Then click on the family you just selected, and then click the download button on the top right of the pop-up.

This will then download the package of fonts as a ZIP folder. Extract the folder into the location of your choice on your device. I usually extract them into the Downloads folder.

Note: One thing to be cautious of when integrating custom fonts into your project is that Android will use the font file name when referencing the font, whereas IOS will use the postscript name. To check the postscript name of the file you will need to use Font Book. So in my example, I will be checking the postscript name of the font Montserrat.

As you can see from the screenshot below, the full name for the Montserrat font is Montserrat Regular; however, the postscript name is Montserrat-Regular, so, if necessary, you’ll need to rename the font files to be the postscript file name. However, with Montserrat the font file name is already like the postscript name, so for this font I don’t have to do it.

The next step is to create a folder in the root of your project that’ll then contain another folder containing the font files you want to add.

For this tutorial, I have created a folder called myassets and inside of that another folder called myfonts. Within the myfonts folder, I have copied the fonts I want to use.

The next step is to create a config file in the root of your project that’ll contain the reference to your assets folder. Using this allows us to link our fonts to Android and iOS using a React-Native link.

The next step of the tutorial depends on what version of React Native you’re using. If you’re using a React Native version greater than 0.60, then you’ll need to create a config file, which I’ll explain how to do below. However, if your React-Native project version is below 0.60, then you can rnpm. I’ll show both below. But I will show the config file first.

So in the root of your project, you’ll need to create a file named react-native.config.js. Don’t worry about the project object for the moment — just ensure the assets value is the same directory file path in your project that contains the font names. This may be different to yours, depending on what you have named the folders.

module.exports = {
project: {
ios: {},
android: {}, // grouped into "project"
},
assets: ["./myassets/myfonts/"], // stays the same
};

However, you can check your React-Native version by entering the below command into the terminal.

react-native -v

It should output something like the following, although both values may be different on your machine.

react-native-cli: 2.0.1
react-native: 0.61.2

If you find that you’re using a version below 0.60, then you’ll need to add rnpm to your package.json file, which will contain the file directory link to your fonts.

In addition, you now need to enter and run this command:

react-native link

This will then link your assets to the Android and iOS folders and create groups/folders in the Xcode and Android Studio projects, if necessary. You can check to see if your font(s) have been added successfully by checking in the iOS info.plist file. If they’re in there, then they have been linked successfully.

The same can be said of your Android project, if you open it using Android Studio, you should be able to see a new folder called “assets” that contains a folder called “fonts,” which will then contain the font files.

This should be it in terms of linking and syncing (haha, see what I did there?) your custom fonts. The next thing is to try them out in your code.

Below is a screenshot of how I’ve implemented the custom font. Update: To see these changes take effect in your project simulator or real phone you may need to close your terminal connection and simulator first, then restart the project.

Finally, below is a screenshot of my custom fonts shown on the React-Native app simulator.

If you have any issues with this tutorial, let me know, and I’ll get back to you ASAP — as in the past, I have struggled a bit with adding custom fonts to my projects. But I think it’s much easier nowadays. That being said, thank you for reading my article!