LearningReactNative
BuildingMobileApplicationswithJavaScript
BonnieEisenman
LearningReactNative
byBonnieEisenman
Copyright©2016BonnieEisenman.Allrightsreserved.
PrintedintheUnitedStatesofAmerica.
PublishedbyO’ReillyMedia,Inc.,1005GravensteinHighwayNorth,Sebastopol,CA
95472.
O’Reillybooksmaybepurchasedforeducational,business,orsalespromotionaluse.
Onlineeditionsarealsoavailableformosttitles().Formore
information,contactourcorporate/institutionalsalesdepartment:800-998-9938or
Editor:MegFoley
ProductionEditor:NicholasAdams
Copyeditor:JasmineKwityn
Proofreader:ChristinaEdwards
Indexer:EllenTroutman-Zaig
InteriorDesigner:DavidFutato
CoverDesigner:RandyComer
Illustrator:RebeccaDemarest
December2015:FirstEdition
RevisionHistoryfortheFirstEdition
2015-12-01:FirstRelease
Seeforreleasedetails.
TheO’ReillylogoisaregisteredtrademarkofO’ReillyMedia,Inc.LearningReact
Native,thecoverimage,andrelatedtradedressaretrademarksofO’ReillyMedia,Inc.
Whilethepublisherandtheauthorhaveusedgoodfaitheffortstoensurethatthe
informationandinstructionscontainedinthisworkareaccurate,thepublisherandthe
authordisclaimallresponsibilityforerrorsoromissions,includingwithoutlimitation
responsibilityfordamagesresultingfromtheuseoforrelianceonthiswork.Useofthe
informationandinstructionscontainedinthisworkisatyourownrisk.Ifanycode
samplesorothertechnologythisworkcontainsordescribesissubjecttoopensource
licensesortheintellectualpropertyrightsofothers,itisyourresponsibilitytoensurethat
yourusethereofcomplieswithsuchlicensesand/orrights.
978-1-491-92900-1
[LSI]
Preface
ThisbookisanintroductiontoReactNative,Facebook’sJavaScriptframeworkfor
buildingmobileapplications.UsingyourexistingknowledgeofJavaScriptandReact,
you’llbeabletobuildanddeployfullyfeaturedmobileapplicationsforbothiOSand
Androidthattrulyrendernatively.Justbecauseit’sJavaScriptdoesn’tmeanweshould
settleforless.ThereareplentyofadvantagestoworkingwithReactNativeover
traditionalmeansofmobiledevelopment,andwedon’tneedtosacrificethenativelook
andfeel.
We’llstartwiththebasics,andworkourwayuptodeployingafull-fledgedapplicationto
boththeiOSAppStoreandtheGooglePlayStore,with100%codereusebetweenthetwo
platforms.Inadditiontotheessentialsoftheframework,we’lldiscusshowtowork
beyondit,includinghowtomakeuseofthird-partylibrariesandevenhowtowriteyour
ownJavaorObjective-ClibrariestoextendReactNative.
Ifyou’recomingtomobiledevelopmentfromtheperspectiveofafrontendsoftware
engineerorwebdeveloper,thisisthebookforyou.ReactNativeisaprettyamazing
thing,andIhopeyou’reasexcitedtoexploreitasIam!
Prerequisites
ThisbookisnotanintroductiontoReact,ingeneral.We’llassumethatyouhavesome
workingknowledgeofReact.Ifyou’rebrandnewtoReact,Isuggestreadingthrougha
tutorialortwobeforecomingbacktotaketheplungeintomobiledevelopment.
Specifically,youshouldbefamiliarwiththeroleofpropsandstate,thecomponent
lifecycle,andhowtocreateReactcomponents.
We’llalsobeusingsomeES6syntax,aswellasJSX.Ifyouaren’tfamiliarwiththese,
don’tworry;we’llcoverJSXinChapter2,andES6syntaxinAppendixA.Thesefeatures
areessentially1:1translationsoftheJavaScriptcodeyou’realreadyaccustomedto
writing.
ThisbookassumesyouaredevelopingonOSX.DevelopingonOSXisarequirementfor
writingiOSapps.LinuxandWindowssupportforwritingAndroidapplicationsisaworkin-progress.YoucanreadmoreaboutLinuxandAndroidsupporthere.
ConventionsUsedinThisBook
Thefollowingtypographicalconventionsareusedinthisbook:
Italic
Indicatesnewterms,URLs,emailaddresses,filenames,andfileextensions.
Constantwidth
Usedforprogramlistings,aswellaswithinparagraphstorefertoprogramelements
suchasvariableorfunctionnames,databases,datatypes,environmentvariables,
statements,andkeywords.
Constantwidthbold
Showscommandsorothertextthatshouldbetypedliterallybytheuser.
Constantwidthitalic
Showstextthatshouldbereplacedwithuser-suppliedvaluesorbyvaluesdetermined
bycontext.
TIP
Thiselementsignifiesatiporsuggestion.
NOTE
Thiselementsignifiesageneralnote.
WARNING
Thiselementindicatesawarningorcaution.
UsingCodeExamples
Supplementalmaterial(codeexamples,exercises,etc.)isavailablefordownloadat:
/>Thisbookisheretohelpyougetyourjobdone.Ingeneral,ifexamplecodeisoffered
withthisbook,youmayuseitinyourprogramsanddocumentation.Youdonotneedto
contactusforpermissionunlessyou’rereproducingasignificantportionofthecode.For
example,writingaprogramthatusesseveralchunksofcodefromthisbookdoesnot
requirepermission.SellingordistributingaCD-ROMofexamplesfromO’Reillybooks
doesrequirepermission.Answeringaquestionbycitingthisbookandquotingexample
codedoesnotrequirepermission.Incorporatingasignificantamountofexamplecode
fromthisbookintoyourproduct’sdocumentationdoesrequirepermission.
Weappreciate,butdonotrequire,attribution.Anattributionusuallyincludesthetitle,
author,publisher,andISBN.Forexample:“LearningReactNativebyBonnieEisenman
(O’Reilly).Copyright2016BonnieEisenman,978-1-491-92900-1.”
Ifyoufeelyouruseofcodeexamplesfallsoutsidefairuseorthepermissiongivenabove,
feelfreetocontactusat
Safari®BooksOnline
NOTE
SafariBooksOnlineisanon-demanddigitallibrarythatdeliversexpertcontentinboth
bookandvideoformfromtheworld’sleadingauthorsintechnologyandbusiness.
Technologyprofessionals,softwaredevelopers,webdesigners,andbusinessandcreative
professionalsuseSafariBooksOnlineastheirprimaryresourceforresearch,problem
solving,learning,andcertificationtraining.
SafariBooksOnlineoffersarangeofplansandpricingforenterprise,government,
education,andindividuals.
Membershaveaccesstothousandsofbooks,trainingvideos,andprepublication
manuscriptsinonefullysearchabledatabasefrompublisherslikeO’ReillyMedia,
PrenticeHallProfessional,Addison-WesleyProfessional,MicrosoftPress,Sams,Que,
PeachpitPress,FocalPress,CiscoPress,JohnWiley&Sons,Syngress,Morgan
Kaufmann,IBMRedbooks,Packt,AdobePress,FTPress,Apress,Manning,NewRiders,
McGraw-Hill,Jones&Bartlett,CourseTechnology,andhundredsmore.Formore
informationaboutSafariBooksOnline,pleasevisitusonline.
HowtoContactUs
Pleaseaddresscommentsandquestionsconcerningthisbooktothepublisher:
O’ReillyMedia,Inc.
1005GravensteinHighwayNorth
Sebastopol,CA95472
800-998-9938(intheUnitedStatesorCanada)
707-829-0515(internationalorlocal)
707-829-0104(fax)
Wehaveawebpageforthisbook,wherewelisterrata,examples,andanyadditional
information.Youcanaccessthispageat />Tocommentorasktechnicalquestionsaboutthisbook,sendemailto
Formoreinformationaboutourbooks,courses,conferences,andnews,seeourwebsiteat
.
FindusonFacebook: />FollowusonTwitter: />WatchusonYouTube: />
Resources
It’sdangeroustogoalone!Well,notreally,butthatdoesn’tmeanyouhaveto.Hereare
someresourcesyoumayfindusefulasyouworkthroughthebook:
TheGitHubrepositoryforthisbookcontainsallofthecodesampleswe’llbe
discussing.Ifyougetstumped,orwantmorecontext,trylookingherefirst.
JointhemailinglistatLearningReactNative.comforfollow-uparticles,suggestions,
andhelpfulresources.
Theofficialdocumentationhasalotofgoodreferencematerial.
Additionally,theReactNativecommunityisausefulresource:
BrentVatne’sReactNativenewsletter
Thereact-nativetagonStackOverflow
#reactnative(irc://chat.freenode.net/reactnative)onFreenode
Acknowledgments
Asistraditional:thisbookwouldnothavebeenpossiblewithoutthehelpandsupportof
manyothers.Thankyoutomyeditor,MegFoley,andtherestoftheO’Reillyteam,for
bringingthisprojectintotheworld.Thankyoualsotomytechnicalreviewers,foryour
timeandinsightfulfeedback:DavidBieber,JasonBrown,EricaPortnoy,andJonathan
Stark.IwouldalsoliketothanktheReactNativeteam,withoutwhosestellarworkthis
bookwouldnaturallybeimpossible.ThanksalsotoZacharyElliotforhishelpwiththe
ZebretoapplicationandAndroidingeneral.
Andmanythanksareowedtomydearfriends,whoputupwithmethroughoutthis
processandprovidedmoralsupport,guidance,anddistraction,asthesituationrequired.
Thankyou.
Chapter1.WhatIsReactNative?
ReactNativeisaJavaScriptframeworkforwritingreal,nativelyrenderingmobile
applicationsforiOSandAndroid.It’sbasedonReact,Facebook’sJavaScriptlibraryfor
buildinguserinterfaces,butinsteadoftargetingthebrowser,ittargetsmobileplatforms.
Inotherwords:webdeveloperscannowwritemobileapplicationsthatlookandfeeltruly
“native,”allfromthecomfortofaJavaScriptlibrarythatwealreadyknowandlove.Plus,
becausemostofthecodeyouwritecanbesharedbetweenplatforms,ReactNativemakes
iteasytosimultaneouslydevelopforbothAndroidandiOS.
SimilartoReactfortheWeb,ReactNativeapplicationsarewrittenusingamixtureof
JavaScriptandXML-esquemarkup,knownasJSX.Then,underthehood,theReact
Native“bridge”invokesthenativerenderingAPIsinObjective-C(foriOS)orJava(for
Android).Thus,yourapplicationwillrenderusingrealmobileUIcomponents,not
webviews,andwilllookandfeellikeanyothermobileapplication.ReactNativealso
exposesJavaScriptinterfacesforplatformAPIs,soyourReactNativeappscanaccess
platformfeatureslikethephonecamera,ortheuser’slocation.
ReactNativecurrentlysupportsbothiOSandAndroid,andhasthepotentialtoexpandto
futureplatformsaswell.Inthisbook,we’llcoverbothiOSandAndroid.Thevast
majorityofthecodewewritewillbecross-platform.Andyes:youcanreallyuseReact
Nativetobuildproduction-readymobileapplications!Someanecdota:Facebook,Palantir,
andTaskRabbitarealreadyusingitinproductionforuser-facingapplications.
AdvantagesofReactNative
ThefactthatReactNativeactuallyrendersusingitshostplatform’sstandardrendering
APIsenablesittostandoutfrommostexistingmethodsofcross-platformapplication
development,likeCordovaorIonic.Existingmethodsofwritingmobileapplications
usingcombinationsofJavaScript,HTML,andCSStypicallyrenderusingwebviews.
Whilethisapproachcanwork,italsocomeswithdrawbacks,especiallyaround
performance.Additionally,theydonotusuallyhaveaccesstothehostplatform’ssetof
nativeUIelements.WhentheseframeworksdotrytomimicnativeUIelements,the
resultsusually“feel”justalittleoff;reverse-engineeringallthefinedetailsofthingslike
animationstakesanenormousamountofeffort,andtheycanquicklybecomeoutofdate.
Incontrast,ReactNativeactuallytranslatesyourmarkuptoreal,nativeUIelements,
leveragingexistingmeansofrenderingviewsonwhateverplatformyouareworkingwith.
Additionally,ReactworksseparatelyfromthemainUIthread,soyourapplicationcan
maintainhighperformancewithoutsacrificingcapability.TheupdatecycleinReact
NativeisthesameasinReact:whenpropsorstatechange,ReactNativere-rendersthe
views.ThemajordifferencebetweenReactNativeandReactinthebrowseristhatReact
NativedoesthisbyleveragingtheUIlibrariesofitshostplatform,ratherthanusing
HTMLandCSSmarkup.
FordevelopersaccustomedtoworkingontheWebwithReact,thismeansyoucanwrite
mobileappswiththeperformanceandlookandfeelofanativeapplication,whileusing
familiartools.ReactNativealsorepresentsanimprovementovernormalmobile
developmentintwootherareas:thedeveloperexperienceandcross-platformdevelopment
potential.
DeveloperExperience
Ifyou’veeverdevelopedformobilebefore,youmightbesurprisedbyhoweasyReact
Nativeistoworkwith.TheReactNativeteamhasbakedstrongdevelopertoolsand
meaningfulerrormessagesintotheframework,soworkingwithrobusttoolsisanatural
partofyourdevelopmentexperience.
Forinstance,becauseReactNativeis“just”JavaScript,youdon’tneedtorebuildyour
applicationinordertoseeyourchangesreflected;instead,youcanhitCommand+Rto
refreshyourapplicationjustasyouwouldanyotherwebpage.Allofthoseminutesspent
waitingforyourapplicationtobuildcanreallyaddup,andincontrastReactNative’s
quickiterationcyclefeelslikeagodsend.
Additionally,ReactNativeletsyoutakeadvantageofintelligentdebuggingtoolsanderror
reporting.IfyouarecomfortablewithChromeorSafari’sdevelopertools(Figure1-1),
youwillbehappytoknowthatyoucanusethemformobiledevelopment,aswell.
Likewise,youcanusewhatevertexteditoryoupreferforJavaScriptediting:ReactNative
doesnotforceyoutoworkinXcodetodevelopforiOS,orAndroidStudioforAndroid
development.
Figure1-1.UsingtheChromeDebugger
Besidestheday-to-dayimprovementstoyourdevelopmentexperience,ReactNativealso
hasthepotentialtopositivelyimpactyourproductreleasecycle.Forinstance,Apple
permitsJavaScript-basedchangestoanapp’sbehaviortobeloadedovertheairwithno
additionalreviewcyclenecessary.
Allofthesesmallperksadduptosavingyouandyourfellowdeveloperstimeandenergy,
allowingyoutofocusonthemoreinterestingpartsofyourworkandbemoreproductive
overall.
CodeReuseandKnowledgeSharing
WorkingwithReactNativecandramaticallyshrinktheresourcesrequiredtobuildmobile
applications.AnydeveloperwhoknowshowtowriteReactcodecannowtargettheWeb,
iOS,andAndroid,allwiththesameskillset.Byremovingtheneedto“silo”developers
basedontheirtargetplatform,ReactNativeletsyourteamiteratemorequickly,andshare
knowledgeandresourcesmoreeffectively.
Besidessharedknowledge,muchofyourcodecanbeshared,too.Notallthecodeyou
writewillbecross-platform,anddependingonwhatfunctionalityyouneedonaspecific
platform,youmayoccasionallyneedtodipintoObjective-CorJava.(Happily,thisisn’t
toobad,andwe’llcoverhowso-callednativemodulesworkinChapter7.)Butreusing
codeacrossplatformsissurprisinglyeasywithReactNative.Forexample,theFacebook
AdsManagerapplicationforAndroidshares87%ofitscodebasewiththeiOSversion,as
notedintheReactEurope2015keynote.Thefinalapplicationwe’lllookatinthisbook,a
flashcardapp,hastotalcodereusebetweenAndroidandiOS.It’shardtobeatthat!
RisksandDrawbacks
Aswithanything,usingReactNativeisnotwithoutitsdownsides,andwhetherornot
ReactNativeisagoodfitforyourteamreallydependsonyourindividualsituation.
ThelargestriskisprobablyReactNative’smaturity,astheprojectisstillrelativelyyoung.
iOSsupportwasreleasedinMarch2015,andAndroidsupportwasreleasedinSeptember
2015.Thedocumentationcertainlyhasroomforimprovement,andcontinuestoevolve.
SomefeaturesoniOSandAndroidstillaren’tsupported,andthecommunityisstill
discoveringbestpractices.Thegoodnewsisthatinthevastmajorityofcases,youcan
implementsupportformissingAPIsyourself,whichwe’llcoverinChapter7.
BecauseReactNativeintroducesanotherlayertoyourproject,itcanalsomakedebugging
hairier,especiallyattheintersectionofReactandthehostplatform.We’llcover
debuggingforReactNativeinmoredepthinChapter8,andtrytoaddresssomeofthe
mostcommonissues.
ReactNativeisstillyoung,andtheusualcaveatsthatgoalongwithworkingwithnew
technologiesapplyhere.Still,onthewhole,Ithinkyou’llseethatthebenefitsoutweigh
therisks.
Summary
ReactNativeisanexcitingframeworkthatenableswebdeveloperstocreaterobustmobile
applicationsusingtheirexistingJavaScriptknowledge.Itoffersfastermobile
development,andmoreefficientcodesharingacrossiOS,Android,andtheWeb,without
sacrificingtheenduser’sexperienceorapplicationquality.Thetradeoffisthatit’snew,
andstillaworkinprogress.Ifyourteamcanhandletheuncertaintythatcomeswith
workingwithanewtechnology,andwantstodevelopmobileapplicationsformorethan
justoneplatform,youshouldbelookingatReactNative.
Inthenextchapter,we’llgooversomeofthemainwaysinwhichReactNativediffers
fromReactfortheWeb,andcoversomekeyconcepts.Ifyou’dliketoskipstraightto
developing,feelfreetojumptoChapter3,inwhichwe’llhandlesettingupour
developmentenvironmentandwriteourveryfirstReactNativeapplication.
Chapter2.WorkingwithReactNative
Inthischapter,we’llcoverthe“bridge,”andreviewhowReactNativeworksunderthe
hood.Then,we’lllookathowReactNativecomponentsdifferfromtheirweb
counterparts,andcoverwhatyou’llneedtoknowinordertocreateandstylecomponents
formobile.
NOTE
Ifyou’dprefertodigintothedevelopmentprocessandseeReactNativeinaction,feelfreetojumpahead
tothenextchapter!