Build cross-plat­form apps with Re­act Na­tive

Dar­ryl Bartlett demon­strates how you can use Re­act Na­tive to build fully func­tional mo­bile apps for iOS and An­droid

net magazine - - CONTENTS - github.com/dar­ryl-bartlett/re­act-na­tive/tree/mas­ter/ YourAp­pName.

Dar­ryl Bartlett demon­strates how you can use Re­act Na­tive to build fully func­tional mo­bile apps for iOS and An­droid

There used to be a time when de­vel­op­ers would need to learn Swift/Ob­jec­tive C to build an iOS app, or Java if they wanted to build an An­droid app. We have now reached an ex­cit­ing time where web de­vel­op­ers can use their ex­ist­ing skills to build both web­sites and apps with­out hav­ing to learn a com­pletely new lan­guage.

Re­act Na­tive is a JavaScript li­brary de­vel­oped by Face­book. It was re­leased back in 2013 and has helped shape apps like Skype, Bloomberg, Wix and many more ( face­book.github.io/re­act-na­tive/show­case.html). Not only can you use your ex­ist­ing knowl­edge of JavaScript but you can also use the same code­base to build for both iOS and An­droid.

GET­TING STARTED

To get started build­ing your Re­act Na­tive project, you will need to make sure that you have Node.js ( nodejs.org/en/) in­stalled. You can then in­stall the cre­ate-re­act-na­tive-app com­mand line util­ity by open­ing a new a ter­mi­nal win­dow and run­ning the fol­low­ing com­mand: npm in­stall - g cre­ate- re­act- na­tive- app You can then cre­ate your new project by run­ning the fol­low­ing com­mand: cre­ate- re­act- na­tive- app YourAp­pName

You will then need to nav­i­gate to your folder via the com­mand line and start the devel­op­ment server. cd myNewApp npm start You can then be­gin work­ing on your app by open­ing the App.js file us­ing a code ed­i­tor.

RUN­NING YOUR APP

Since you used cre­ate-re­act-na­tive-app via the com­mand line to build your project, you can use the Expo client app to test your ap­pli­ca­tion. All you need to do is down­load the app from the iOS App Store or Google Play Store and then scan the QR code from in­side the ter­mi­nal. You will need to make sure your de­vice is on the same Wi-Fi net­work as your com­puter. You can also use the iPhone or An­droid sim­u­la­tor, if you have Xcode or An­droid Stu­dio in­stalled.

BA­SIC RE­ACT NA­TIVE EX­AM­PLE

Let’s start by adding some­thing very ba­sic. To add some text to your ap­pli­ca­tion, you will need to type: <Text>Lo­gin Page<Text> Work­ing with styles is very sim­i­lar to CSS. If you wanted to add a style to the line of text that you just cre­ated, you would sim­ply edit that line of text to: <Text style={styles. main­header}> My Lo­gin App</ Text> You can then add the text style un­der Stylesheet.cre­ate. main­header: { color: ‘# 000066’, tex­tAlign: ‘cen­ter’, fontSize: 16 }, We are now go­ing to cre­ate a fully func­tional lo­gin screen so that users can lo­gin, reg­is­ter for a new ac­count, sign out and even re­set their pass­word. This is some­thing you will see a lot in mo­bile apps, so it lays down a nice foun­da­tion for fu­ture projects.

SET­TING UP FIREBASE AND NA­TIVE BASE

We are go­ing to start by in­stalling three more li­braries. The first is called Firebase, which is what we will use for our user au­then­ti­ca­tion, and the se­cond is called Na­tiveBase, which is a UI com­po­nent li­brary. The last one is called Re­act Na­tive Di­a­log In­put, which en­ables us to dis­play a di­a­logue box where users can en­ter text. Nav­i­gate to your project folder us­ing the com­mand line and en­ter the be­low: npm in­stall firebase npm in­stall na­tive- base npm in­stall -- save re­act- na­tive- di­a­log- in­put Make sure you im­port Firebase, Na­tiveBase and Re­act Na­tive Di­a­log In­put at the top of the App.js file. im­port * as firebase from ‘ firebase’; im­port { Con­tainer, Con­tent, Header, Form, In­put, Item,

“Not only can you use your ex­ist­ing knowl­edge of JS but you can also use the same code­base for both iOS and An­droid”

“We’re go­ing to cre­ate a lo­gin screen so users can lo­gin, reg­is­ter for an ac­count, sign out and re­set their pass­word”

But­ton, La­bel } from ‘na­tive- base’ im­port DialogIn­put from ‘re­act- na­tive- di­a­log- in­put’;

Next, we will need to setup the Firebase con­fig just un­der­neath the im­port com­mands. You will need to go and setup an ac­count with Firebase to get your var­i­ous set­tings. You can do this by reg­is­ter­ing at firebase.google.com and cre­at­ing a new project. Re­mem­ber that you will need to en­able email and pass­word au­then­ti­ca­tion from the dash­board.

var con­fig = { apiKey: “< API_KEY>”, au­thDo­main: “<PROJECT_ID>. fire­baseapp. com”, databaseURL: “https://<DATABASE_NAME>. fire­ba­seio. com”, pro­jec­tId: “<PROJECT_ID>”, stor­ageBucket: “<BUCKET>. appspot. com”, mes­sag­ingSen­derId: “< SENDER_ID>” }; firebase. ini­tial­izeApp(con­fig);

BuILD­ING THE CON­TAINER

The next step is to re­move the <View> sec­tion un­der­neath ren­der(), which was au­to­mat­i­cally placed there by Re­act upon cre­at­ing the project, and re­place it with the fol­low­ing con­tainer to setup the lo­gin form. The form will con­tain a la­bel and an in­put field for both an email ad­dress and pass­word. We will also cre­ate three but­tons: one to lo­gin, one to sign up and the fi­nal but­ton is for when a user wants to re­set their pass­word. We will set a mar­gin at the top of each but­ton to 10 pixels and set the font colour to white.

< Con­tainer style={styles. con­tainer}> <Text style={styles. main­header}>Lo­gin Page</ Text> <Form> <Item> <La­bel>Email</ La­bel> <In­put

au­to­cor­rect={false}> </ Item> <Item> <La­bel>Pass­word</ La­bel> <In­put se­cureTex­tEn­try={true}> </ Item> <But­ton style={{marginTop:10}} pri­mary full rounded> <Text style={{color: ‘ white’}}> Lo­gin</ Text> </ But­ton> <But­ton style={{marginTop:10}} suc­cess full rounded> <Text style={{color: ‘ white’}}>Sign Up</ Text> </ But­ton> <But­ton style={{marginTop:10}} warn­ing full rounded>

<Text style={{color: ‘ white’}}>For­got Pass­word</

Text> </ But­ton> </ Form> </Con­tainer>

SET­TING UP THE EVENTS

Firstly, we need to set up a con­struc­tor to set up the de­fault state. The email and pass­word de­fault val­ues will be set to empty. We will also set the value of

isDialogVis­i­ble to false: this is go­ing to be used for our pass­word re­set di­a­log box later on.

con­struc­tor( props) { su­per( props) this. state=({ email: ‘’, pass­word: ‘’, isDialogVis­i­ble: false }) }

We will now add onChangeText events to both of our text in­puts, so that ev­ery time the user types some­thing into the email or pass­word fields, it will up­date the state of both email and pass­word to that value.

onChangeText={(email) => this. setS­tate({ email })} onChangeText={( pass­word) => this. setS­tate({ pass­word })}

We also need to add onPress func­tions to our lo­gin, sign-up and for­got­ten pass­word but­tons. Each one will call a dif­fer­ent func­tion. The lo­gin but­ton will call a func­tion called loginUser, the sign-up but­ton will call signUpUser and the for­got­ten pass­word but­ton will call for­gotPass­word.

onPress={() => this. loginUser( this. state. email, this. state. pass­word)}’ onPress={() => this. signUpUser( this. state. email, this. state.

pass­word)} onPress={() => this. for­gotPass­word()}

SIGN-UP FUNC­TION

It’s now time to be­gin build­ing out our func­tions. We will be­gin with the sign-up func­tion ( signUpUser), which will at­tempt to cre­ate a new user in­side Firebase; if it suc­ceeds, then we will dis­play an on­screen alert to in­form the user that their ac­count has been set up. How­ever, if the user chooses a pass­word that is less six char­ac­ters in length, it will prompt them to en­ter some­thing that is a min­i­mum of six char­ac­ters long. Fi­nally, we need to add the catch er­ror han­dler, so that if the sign-up at­tempt fails through Firebase, we will print the er­ror mes­sage to the con­sole.

signUpUser = (email, pass­word) => { try { if( this. state. pass­word. length< 6) { alert(“Please en­ter at least 6 char­ac­ters”) re­turn; } firebase. auth(). cre­ateUserWithE­mailAndPass­word(ema il, pass­word)

alert(“Con­grat­u­la­tions, your ac­count has been setup”) } catch(er­ror){ con­sole. log(er­ror.toString()) } }

LO­GIN FUNC­TION

Next, we will add the lo­gin ( loginUser) func­tion. This will try to log in the user with their email and pass­word. If the user suc­cess­fully signs in, it will dis­play an alert to say that sign-in was suc­cess­ful, along with a sign out but­ton. Once again, we will need to make sure we add a catch er­ror han­dler in case there is an er­ror with the lo­gin at­tempt.

loginUser = (email, pass­word) => { try {

“The loginUser func­tion will try to lo­gin the user with the email and pass­word that has been sup­plied”

firebase. auth(). signInWithE­mailAndPass­word(email, pass­word).then((user) =>{ Alert. alert( ‘ Signed In’, ‘ You have signed in. Well done!’, [

{text: ‘ Sign Out’, onPress: this. signOutUser}, ], { can­ce­lable: false } ) }) } catch(er­ror) {

con­sole. log(er­ror.toString()) } }

SIGN OUT-FUNC­TION

It’s now on to the sign-out func­tion, which en­sures that the user is signed out once they click the sign out but­ton on the alert.

signOutUser = () => { firebase. auth(). signOut().then( func­tion (user){ }). catch( func­tion(er­ror) {

con­sole. log(er­ror) }); }

FOR­GOT PASS­WORD FUNC­TION

To fin­ish off our project, we are go­ing to build out a func­tion that will en­able the user to eas­ily re­set their pass­word in case they’ve ei­ther for­got­ten it or want to change it for some other rea­son. First, we need to cre­ate the di­a­log box just out­side of our <form> tags.

<DialogIn­put isDialogVis­i­ble={this. state. isDialogVis­i­ble} ti­tle={“For­got Pass­word”} mes­sage={“Please in­put your email ad­dress”} hin­tIn­put ={“john@ test. com”} sub­mitIn­put={ (usere­mail) => {this. sendRe­set(usere­mail)} } closeDia­log={ () => { this. setS­tate({ isDialogVis­i­ble: this. state. isDialogVis­i­ble = false })}}> </ DialogIn­put>

We now need to make the di­a­log box ap­pear, so we will cre­ate the for­gotPass­word func­tion, which will change the state of isDialogVis­i­ble to true.

for­gotPass­word = () => { this. setS­tate({ isDialogVis­i­ble: this. state. isDialogVis­i­ble = true }) }

The di­a­log box will prompt the user to en­ter their email ad­dress. If the user clicks the can­cel but­ton, then the box will close, as it changes the state of the isDialogVis­i­ble back to false. If the user clicks the sub­mit but­ton then it will call a func­tion called

sendRe­set along with the email ad­dress. In­side our sendRe­set, we will use the email ad­dress to cre­ate the Firebase sendPass­wordRe­setE­mail re­quest.

sendRe­set = (usere­mail) => { var auth = firebase. auth(); auth. sendPass­wordRe­setE­mail(usere­mail).then( func­tion() { alert(“Pass­word re­set email has been sent”) }). catch( func­tion(er­ror) { con­sole. log(er­ror) }); }

CON­CLU­SION

This is a great start­ing point for your own app and it could eas­ily be im­proved upon by adding more screens, dis­play­ing er­rors on the front end and much more. I hope this project has helped you un­der­stand the pos­si­bil­i­ties that are avail­able with Re­act Na­tive. Don’t for­get that you can grab the project files at

Dar­ryl Bart­let t w: job: ar­eas of ex­per­tise: bartlettdar­ryl.com Front- end de­vel­oper JavaScript, PHP, Mo­bile Devel­op­ment

Top Since you used cre­atere­act-na­tive-app via the com­mand line, you can use the Expo client app to test your ap­pli­ca­tion Above We’re now go­ing to cre­ate a fully func­tional lo­gin screen so users can lo­gin, reg­is­ter and sign out

Above Firebase is what we will use for our user au­then­ti­ca­tion. We will need to setup the Firebase con­fig just un­der­neath the im­port com­mands

Above We will also cre­ate three but­tons: one to lo­gin, one to sign up and the fi­nal but­ton is for when a user wants to re­set their pass­word

TopIf the user suc­cess­fully signs in, it will dis­play an alert to say the sign in was suc­cess­fully, along with a sign out but­ton

Newspapers in English

Newspapers from Australia

© PressReader. All rights reserved.