Title | React handbook |
---|---|
Author | anayeat rabbi khan |
Course | Electricity, Magnetism and Electrical Circuit Lab |
Institution | Royal University of Dhaka |
Pages | 207 |
File Size | 5.8 MB |
File Type | |
Total Downloads | 2 |
Total Views | 152 |
React book for web...
TableofContents Introduction Overview IntroductiontoReact HowtoinstallReact ModernJavaScriptcoreconceptsyouneedtoknowtouseReact HowmuchJSyouneedtouseReact Variables Arrowfunctions WorkwithobjectsandarraysusingRestandSpread Objectandarraydestructuring Templateliterals Classes Callbacks Promises Async/Await ESModules ReactConcepts SinglePageApps Declarative Immutability Purity Composition TheVirtualDOM UnidirectionalDataFlow In-depth JSX Components State Props Presentationalvscontainercomponents
2
StatevsProps PropTypes Fragment Events Lifecycleevents Handlingforms ReferenceaDOMelement Serversiderendering ContextAPI Higher-ordercomponents RenderProps Hooks Codesplitting Styling CSSinReact SASSwithReact StyledComponents Tooling Babel Webpack Prettier Testing IntroductiontoJest TestingReactComponents AlookattheReactEcosystem ReactRouter Redux Next.js Gatsby Wrappingup
3
4
Introduction
Introduction
TheReactHandbookfollowsthe80/20rule:learnin20%ofthetimethe80%ofatopic. Ifindthisapproachgivesawell-roundedoverview.Thisbookdoesnottrytocovereverything underthesunrelatedtoReact.Ifyouthinksomespecifictopicshouldbeincluded,tellme. InthisbookImakeuseofReacthooks,soyouneedtosettherequiredversionsofReactand ReactDOMtouse 16.7.0-alpha.2(ifwhenyou'rereadingthisHooksarereleasedofficially, youdon'tneedtodothis).YoucandosoinCodeSandboxbyclicking"AddDependency"and searching reactandchoosing 16.7.0-alpha.2fromtheselect,andrepeatthisfor reactdom.Whenusing create-react-app,run npminstall[email protected][email protected]afteryoucreatetheproject.
Ihopethecontentsofthisbookwillhelpyouachievewhatyouwant:learnthebasicsof React. ThisbookiswrittenbyFlavio.Ipublishwebdevelopmenttutorialseverydayonmywebsite flaviocopes.com. YoucanreachmeonTwitter@flaviocopes.
5
Introduction
Enjoy!
6
IntroductiontoReact
IntroductiontoReact AnintroductiontotheReactviewlibrary
WhatisReact? ReactisaJavaScriptlibrarythataimstosimplifydevelopmentofvisualinterfaces. DevelopedatFacebookandreleasedtotheworldin2013,itdrivessomeofthemostwidely usedapps,poweringFacebookandInstagramamongcountlessotherapplications. Itsprimarygoalistomakeiteasytoreasonaboutaninterfaceanditsstateatanypointin time,bydividingtheUIintoacollectionofcomponents.
WhyisReactsopopular? Reacthastakenthefrontendwebdevelopmentworldbystorm.Why?
Lesscomplexthantheotheralternatives AtthetimewhenReactwasannounced,Ember.jsandAngular1.xwerethepredominant choicesasaframework.Boththeseimposedsomanyconventionsonthecodethatportingan existingappwasnotconvenientatall.Reactmadeachoicetobeveryeasytointegrateinto anexistingproject,becausethat'showtheyhadtodoitatFacebookinordertointroduceitto theexistingcodebase.Also,those2frameworksbroughttoomuchtothetable,whileReact onlychosetoimplementtheViewlayerinsteadofthefullMVCstack.
Perfecttiming Atthetime,Angular2.xwasannouncedbyGoogle,alongwiththebackwardsincompatibility andmajorchangesitwasgoingtobring.MovingfromAngular1to2waslikemovingtoa differentframework,sothis,alongwithexecutionspeedimprovementsthatReactpromised, madeitsomethingdeveloperswereeagertotry.
BackedbyFacebook BeingbackedbyFacebookobviouslyisgoingtobenefitaprojectifitturnsouttobe successful.
7
IntroductiontoReact
FacebookcurrentlyhasastronginterestinReact,seesthevalueofitbeingOpenSource,and thisisahugeplusforallthedevelopersusingitintheirownprojects.
IsReactsimpletolearn? EventhoughIsaidthatReactissimplerthanalternativeframeworks,divingintoReactisstill complicated,butmostlybecauseofthecorollarytechnologiesthatcanbeintegratedwith React,likeReduxandGraphQL. ReactinitselfhasaverysmallAPI,andyoubasicallyneedtounderstand4conceptstoget started: Components JSX State Props Allthese(andmore)areexplainedinthishandbook.
8
HowtoinstallReact
HowtoinstallReact HowtoinstallReactonyourdevelopmentcomputer HowdoyouinstallReact? Reactisalibrary,sosayinginstallmightsoundabitweird.Maybesetupisabetterword,but yougettheconcept. TherearevariouswaystosetupReactsothatitcanbeusedonyourapporsite.
LoadReactdirectlyinthewebpage ThesimplestoneistoaddtheReactJavaScriptfileintothepagedirectly.Thisisbestwhen yourReactappwillinteractwiththeelementspresentonasinglepage,andnotactually controlsthewholenavigationaspect. Inthiscase,youadd2scripttagstotheendofthe bodytag:
... ...
The 16.7.0-alpha.2versioninthelinkspointstothelatestAlphaof16.7(atthetimeof writing),whichhasHooksavailable.PleasechangeittothelatestversionofReactthatis available. HereweloadedbothReactandReactDOM.Why2libraries?BecauseReactis100% independentfromthebrowserandcanbeusedoutsideit(forexampleonMobiledeviceswith ReactNative).HencetheneedforReactDOM,toaddthewrappersforthebrowser.
9
HowtoinstallReact
AfterthosetagsyoucanloadyourJavaScriptfilesthatuseReact,oreveninlineJavaScriptin a scripttag:
, document.getElementById('app') )
ABrowserRoutercomponentcanonlyhaveonechildelement,sowewrapallwe'regoingto addina divelement.
Link TheLinkcomponentisusedtotriggernewroutes.Youimportitfrom react-router-dom,and youcanaddtheLinkcomponentstopointatdifferentroutes,withthe toattribute: importReactfrom'react' importReactDOMfrom'react-dom' import{BrowserRouterasRouter,Link}from'react-router-dom' ReactDOM.render( Dashboard About , document.getElementById('app') )
Route Nowlet'saddtheRoutecomponentintheabovesnippettomakethingsactuallyworkaswe want:
178
ReactRouter
importReactfrom'react' importReactDOMfrom'react-dom' import{BrowserRouterasRouter,Link,Route}from'react-router-dom' constDashboard=()=>( Dashboard ... ) constAbout=()=>( About ... ) ReactDOM.render( Dashboard About , document.getElementById('app') )
CheckthisexampleonGlitch:https://flaviocopes-react-router-v4.glitch.me/ Whentheroutematches /,theapplicationshowstheDashboardcomponent. Whentherouteischangedbyclickingthe"About"linkto /about,theDashboardcomponent isremovedandtheAboutcomponentisinsertedintheDOM. Noticethe exactattribute.Withoutthis, path="/"wouldalsomatch /about,since /is containedintheroute.
Matchmultiplepaths Youcanhavearouterespondtomultiplepathssimplyusingaregex,because pathcanbea regularexpressionsstring:
179
ReactRouter
Inlinerendering Insteadofspecifyinga componentpropertyon Route,youcanseta renderprop: ( About ... )} />
Matchdynamicrouteparameter Youalreadysawhowtousestaticrouteslike constPosts=()=>( Posts ... ) //...
Here'showtohandledynamicroutes: constPost=({match})=>( Post#{match.params.id} ... ) //...
InyourRoutecomponentyoucanlookupthedynamicparametersin match.params.
180
ReactRouter
matchisalsoavailableininlinerenderedroutes,andthisisespeciallyusefulinthiscase,
becausewecanusethe idparametertolookupthepostdatainourdatasourcebefore renderingPost: constposts=[ {id:1,title:'First',content:'Helloworld!'}, {id:2,title:'Second',content:'Helloagain!'} ] constPost=({post})=>( {post.title} {post.content} ) //... ( p.id===match.params.id)}/> )}/>
181
Redux
Redux Reduxisastatemanagerthat'susuallyusedalongwithReact,butit'snot tiedtothatlibrary.LearnReduxbyreadingthissimpleandeasytofollow guide
WhyyouneedRedux Reduxisastatemanagerthat'susuallyusedalongwithReact,butit'snottiedtothatlibraryitcanbeusedwithothertechnologiesaswell,butwe'llsticktoReactforthesakeofthe explanation. Reacthasitsownwaytomanagestate,asyoucanreadontheReactBeginner'sGuide, whereIintroducehowyoucanmanageStateinReact. Movingthestateupinthetreeworksinsimplecases,butinacomplexappyoumightfindyou aremovingalmostallthestateup,andthendownusingprops. Reactinversion16.3.0introducedtheContextAPI,whichmakesReduxredundantforthe usecaseofaccessingthestatefromdifferentpartsofyourapp,soconsiderusingtheContext APIinsteadofRedux,unlessyouneedaspecificfeaturethatReduxprovides. Reduxisawaytomanageanapplicationstate,andmoveittoanexternalglobalstore. Thereareafewconceptstograsp,butonceyoudo,Reduxisaverysimpleapproachtothe problem. ReduxisverypopularwithReactapplications,butit'sinnowayuniquetoReact:thereare bindingsfornearlyanypopularframework.Thatsaid,I'llmakesomeexamplesusingReactas itisitsprimaryusecase.
WhenshouldyouuseRedux? Reduxisidealformediumtobigapps,andyoushouldonlyuseitwhenyouhavetrouble managingthestatewiththedefaultstatemanagementofReact,ortheotherlibraryyouuse. Simpleappsshouldnotneeditatall(andthere'snothingwrongwithsimpleapps).
ImmutableStateTree
182
Redux
InRedux,thewholestateoftheapplicationisrepresentedbyoneJavaScriptobject,called StateorStateTree. WecallitImmutableStateTreebecauseitisreadonly:itcan'tbechangeddirectly. ItcanonlybechangedbydispatchinganAction.
Actions AnActionisaJavaScriptobjectthatdescribesachangeinaminimalway(withjustthe informationneeded): { type:'CLICKED_SIDEBAR' } //e.g.withmoredata { type:'SELECTED_USER', userId:232 }
Theonlyrequirementofanactionobjectishavinga typeproperty,whosevalueisusuallya string.
Actionstypesshouldbeconstants Inasimpleappanactiontypecanbedefinedasastring,asIdidintheexampleinthe previouslesson. Whentheappgrowsisbesttouseconstants: constADD_ITEM='ADD_ITEM' constaction={type:ADD_ITEM,title:'Thirditem'}
andtoseparateactionsintheirownfiles,andimportthem import{ADD_ITEM,REMOVE_ITEM}from'./actions'
Actioncreators ActionsCreatorsarefunctionsthatcreateactions. functionaddItem(t){
183
Redux
return{ type:ADD_ITEM, title:t } }
Youusuallyrunactioncreatorsincombinationwithtriggeringthedispatcher: dispatch(addItem('Milk'))
orbydefininganactiondispatcherfunction: constdispatchAddItem=i=>dispatch(addItem(i)) dispatchAddItem('Milk')
Reducers Whenanactionisfired,somethingmusthappen,thestateoftheapplicationmustchange. Thisisthejobofreducers.
Whatisareducer AreducerisapurefunctionthatcalculatesthenextStateTreebasedonthepreviousState Tree,andtheactiondispatched. ;(currentState,action)=>newState
Apurefunctiontakesaninputandreturnsanoutputwithoutchangingtheinputoranything else.Thus,areducerreturnsacompletelynewstatetreeobjectthatsubstitutestheprevious one.
Whatareducershouldnotdo Areducershouldbeapurefunction,soitshould: nevermutateitsarguments nevermutatethestate,butinsteadcreateanewonewith Object.assign({},...) nevergenerateside-effects(noAPIcallschanginganything) nevercallnon-purefunctions,functionsthatchangetheiroutputbasedonfactorsother thantheirinput(e.g. Date.now()or Math.random())
184
Redux
Thereisnoreinforcement,butyoushouldsticktotherules.
Multiplereducers Sincethestateofacomplexappcouldbereallywide,thereisnotasinglereducer,butmany reducersforanykindofaction.
Asimulationofareducer Atitscore,Reduxcanbesimplifiedwiththissimplemodel:
Thestate { list:[ {title:"Firstitem"}, {title:"Seconditem"}, ], title:'Grocerieslist' }
Alistofactions {type:'ADD_ITEM',title:'Thirditem'} {type:'REMOVE_ITEM',index:1} {type:'CHANGE_LIST_TITLE',title:'Roadtriplist'}
Areducerforeverypartofthestate consttitle=(state='',action)=>{ if(action.type==='CHANGE_LIST_TITLE'){ returnaction.title }else{ returnstate } } constlist=(state=[],action)=>{ switch(action.type){ case'ADD_ITEM': returnstate.concat([{title:action.title}]) case'REMOVE_ITEM': returnstate.map((item,index)=> action.index===index ?{title:item.title} :item
185
Redux
default: returnstate } }
Areducerforthewholestate constlistManager=(state={},action)=>{ return{ title:title(state.title,action), list:list(state.list,action) } }
TheStore TheStoreisanobjectthat: holdsthestateoftheapp exposesthestatevia getState() allowsustoupdatethestatevia dispatch() allowsusto(un)registerastatechangelistenerusing subscribe() Astoreisuniqueintheapp. HereishowastoreforthelistManagerappiscreated: import{createStore}from'redux' importlistManagerfrom'./reducers' letstore=createStore(listManager)
CanIinitializethestorewithserver-sidedata? Sure,justpassastartingstate: letstore=createStore(listManager,preexistingState)
Gettingthestate store.getState()
Updatethestate 186
Redux
store.dispatch(addItem('Something'))
Listentostatechanges constunsubscribe=store.subscribe(()=> constnewState=store.getState() ) unsubscribe()
DataFlow DataflowinReduxisalwaysunidirectional. Youcall dispatch()ontheStore,passinganAction. TheStoretakescareofpassingtheActiontotheReducer,generatingthenextState. TheStoreupdatestheStateandalertsalltheListeners.
187
Next.js
Next.js Next.jsisaverypopularNode.jsframeworkwhichenableseasyserver-side Reactrendering,andprovidesmanyotheramazingfeatures
WorkingonamodernJavaScriptapplicationpoweredbyReactisawesomeuntilyourealize thatthereareacoupleproblemsrelatedtorenderingallthecontentontheclient-side. First,thepagetakeslongertothebecomevisibletotheuser,becausebeforethecontent loads,alltheJavaScriptmustload,andyourapplicationneedstoruntodeterminewhatto showonthepage. Second,ifyouarebuildingapubliclyavailablewebsite,youhaveacontentSEOissue.Search enginesaregettingbetteratrunningandindexingJavaScriptapps,butit'smuchbetterifwe cansendthemcontentinsteadoflettingthemfigureitout. Thesolutiontobothofthoseproblemsisserverrendering,alsocalledstaticpre-rendering. Next.jsisoneReactframeworktodoallofthisinaverysimpleway,butit'snotlimitedtothis. It'sadvertisedbyitscreatorsasazero-configuration,single-commandtoolchainforReact apps. ItprovidesacommonstructurethatallowsyoutoeasilybuildafrontendReactapplication, andtransparentlyhandleserver-siderenderingforyou.
188
Next.js
Mainfeatures Hereisanon-exhaustivelistofthemainNext.jsfeatures: HotCodeReloading:Next.jsreloadsthepagewhenitdetectsanychangesavedtodisk. AutomaticRouting:anyURLismappedtothefilesystem,tofilesputinthe pages folder,andyoudon'tneedanyconfiguration(youhavecustomizationoptionsofcourse). SingleFileComponents:usingstyled-jsx,completelyintegratedasbuiltbythesame team,it'strivialtoaddstylesscopedtothecomponent. ServerRendering:youcan(optionally)renderReactcomponentsontheserverside, beforesendingtheHTMLtotheclient. EcosystemCompatibility:Next.jsplayswellwiththerestoftheJavaScript,Nodeand Reactecosystem. AutomaticCodeSplitting:pagesarerenderedwithjustthelibrariesandJavaScriptthat theyneed,nomore. Prefetching:the Linkcomponent,usedtolinktogetherdifferentpages,supportsa prefetchpropwhichautomaticallyprefetchespageresources(includingcodemissing
duetocodesplitting)inthebackground. DynamicComponents:youcanimportJavaScriptmodulesandReactComponents dynamically(https://github.com/zeit/next.js#dynamic-import). StaticExports:usingthe nextexportcommand,Next.jsallowsyoutoexportafully staticsitefromyourapp.
Installation Next.jssupportsallthemajorplatforms:Linux,macOS,Windows. ANext.jsprojectisstartedeasilywithnpm: npminstallnextreactreact-dom
orwithYarn: yarnaddnextreactreact-dom
Gettingstarted Createa package.jsonfilewiththiscontent:
189
Next.js
{ "scripts":{ "dev":"next" } }
Ifyourunthiscommandnow: npmrundev
thescriptwillraiseanerrorcomplainingaboutnotfindingthe pagesfolder.Thisistheonly thingthatNext.jsrequirestorun. Createanempty pagesfolder,andrunthecommandagain,andNext.jswillstartupaserver on localhost:3000. IfyougotothatURLnow,you'llbegreetedbyafriendly404page,withanicecleandesign.
Next.jshandlesothererrortypesaswell,like500errorsforexample.
Createapage Inthe pagesfoldercreatean index.jsfilewithasimpleReactfunctionalcomponent: exportdefault()=>( HelloWorld! )
Ifyouvisit localhost:3000,thiscomponentwillautomaticallyberendered.
190
Next.js
Whyisthissosimple? Next.jsusesadeclarativepagesstructure,whichisbasedonthefilesystemstructure. Simplyput,pagesareinsidea pagesfolder,andthepageURLisdeterminedbythepagefile name.ThefilesystemisthepagesAPI.
Server-siderendering Openthepagesource, View->Developer->ViewSourcewithChrome. Asyoucansee,theHTMLgeneratedbythecomponentissentdirectlyinthepagesource.It's notrenderedclient-side,butinsteadit'srenderedontheserver. TheNext.jsteamwantedtocreateadeveloperexperienceforserverrenderedpagessimilar totheoneyougetwhencreatingabasicPHPproject,whereyousimplydropPHPfilesand youcallthem,andtheyshowupaspages.Internallyofcourseit'sallverydifferent,butthe apparenteaseofuseisclear.
Addasecondpage Let'screateanotherpage,in pages/contact.js exportdefault()=>( Contactus! )
Ifyoupointyourbrowserto localhost:3000/contactthispage...