React From Scratch, Book 2: Hooks and forms Build your porfolio with hooks and forms Ajdin Imsirovic Thisbookisforsaleathttp://leanpub.com/react-from-scratch-book-2-hooks-and-forms Thisversionwaspublishedon2023-01-19 ThisisaLeanpubbook.LeanpubempowersauthorsandpublisherswiththeLeanPublishing process.LeanPublishingistheactofpublishinganin-progressebookusinglightweighttoolsand manyiterationstogetreaderfeedback,pivotuntilyouhavetherightbookandbuildtractiononce youdo. ©2023AjdinImsirovic Contents Chapter0:Beforewestart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 0.1Disclaimer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 0.2Assumptions:Thingstohaveandknowbeforewestart . . . . . . . . . . . . . . . . . . . . 2 0.3Whatthisbookisabout? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Chapter1:UnderstandingtheuseStatehook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 1.1Updatingacomponent’sstateusingtheuseStatehook . . . . . . . . . . . . . . . . . . . . . 6 Chapter2:FormsinReact . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 2.1FormsinReact . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 2.2WatchforinputchangesinReact . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 2.3DetectingandhandlingtheonChangeeventonaninput . . . . . . . . . . . . . . . . . . . . 13 2.4Addingthebuilt-ineventobject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 2.5Addingstatetotheforminput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 2.6TheproperwayofupdatingthestateobjectinReact . . . . . . . . . . . . . . . . . . . . . . 19 2.6Addingtheageinput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 2.7ControlledcomponentsinReact . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 2.8Otherforminputs:radiobuttons,checkboxes,textareas,andselects . . . . . . . . . . . . 31 2.9FormsubmissionandpreventDefault . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 2.10??? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 Chapter3:RevisingcomponentsandJSX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 3.1asdf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Chapter4:Buildatodoapp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 4.1asdf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 Chapter5:Popularformlibraries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 5.1asdf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Chapter6:Popularcomponentlibraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 6.1asdf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 Chapter7:Buildaportfolioapp. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 7.1asdf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 CONTENTS Chapter8:DeployaportfolioapptoNetlify. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 8.1asdf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 Chapter 0: Before we start 0.1 Disclaimer Before I even begin, note that this disclaimer is exactly the same as the one in the first book in this bookseries.So,ifyou’vereaditinthepreviousbook,youcanskiptothenextsection. Here goes the not-so-obligatory information that most people skip - but, I kept it really short and sweet-underonepage. Give it a try - I’ve tried my best to give you some context in this section and some of my thoughts beforewegointothetopicofthe book. Heregoes. I’vetriedmybesttomakethisbookasuccess. But,I’monlyanotherguy,and,likethevastmajorityofpeople,Idomakemistakes. I hope that you, dear reader, will be able to appreciate the intention and the effort I have put into writing this book. It is a product of many, many hours spent in front of a computer monitor, either writingaboutcode,thinkingaboutcode,debuggingsomecode,orjustplaincoding.Idon’ttakethis effortlightly.It’smysourceofpride-andthereasonwhyIfeelcompetenttowritethisbook. I’d say I’m way past the 10 thousand hours of deliberate practice, the concept popularised by MalcolmGladwellinhisbookOutliers. So,whoamIandwhyshouldyoulistentomyadvice? Well, I’ve already sort of answered that question above. I’m just another guy; a self-taught web developerwhohasspentyearsmasteringmycraft. In some parts of the web development world, I’m a seasoned veteran. In some other parts of it, I’m anewbie. I’mnotaknow-it-all,ifsuchapersonexists. ButIhavededicatedalargepartofmyprofessionalcareertowritingtutorialsonwebdevelopment, writingbooksaboutit,andthinkingaboutbestwaystotransferknowledge.Readinguponittoo! SoI’dsayI’vebecomecompetenttoteachthissubject,basedonmyexperience. Ifyoufindthisbooknottoyourliking,luckily,Leanpubhasareallygenerous60-dayreturnpolicy. You might say that’s as risk-free as it can get. You can’t really say that it cost a fortune to begin with, and the return policy is working in your favor anyway. So if you strongly feel that this book isdoingyounogood-please,byallmeans,returnit.Noreasontogetworkedupaboutit,eitheron mysideoronyours. Chapter0: Beforewestart 2 Ifyouhavecomplaintsaboutthebook,[email protected]’lldo mybesttodealwiththeissue. Also,anycommentsandkindwords,aswellasharshcriticisms,areallwelcome. Kindwordsfromreadersmeanalot. Harsh criticisms, while I do find them usually not really neccessary, are a way to point me in the rightdirection-andultimatelyhelpmebecomeabettertechnicalwriterandabetterdeveloper. SoIthankyoueitherway. 0.2 Assumptions: Things to have and know before we start Ifyou’restartingthisbook,IexpectyouatleasthaveNode.jsandNPMinstalledonyourmachine. IalsoexpectthatyouknoweverythingI’vecoveredinBook1ofthisbookseries. Ideally, you’d have gone through the contents of that book and you’re ready to continue with this one. If you haven’t gone through the first book, perhaps some chapters in this one might be a bit challenging. Howcanyoudetermineifthat’sgoingtobethecaseforyou? Well,here’sanoverviewofthingscoveredinBook1. 0.2.1 Things covered in Chapter 1: Simplest app Inthischapter: 1. I’veshowntoyouhowtoinstallReactDeveloperToolsinyourbrowser. 2. I’ve introduced you to the create-react-app npm package, and I’ve shown to you how to use thispackagetobuildaboilerplateReactapp. 3. I’ve explained all the files and folders in that boilerplate app, which goes a long way, because nowyou’llunderstandthebasicstructureofanyReactappbuiltusingthispackage 4. I’veshownhowyoucanupdatethisstarterapptochangeitsoutput 0.2.2 Things covered in Chapter 2: Serving React from a CDN Inthischapter,I’veshowntoyou: 1. HowtobuildaReactappwithoutabuildstep(usingCodepen.io) Chapter0: Beforewestart 3 2. Howtorendermultipleheadingelements 3. HowtouseReact.createElement 4. TheDOMincontextofReact 5. Improvingyourapp’scodewithJSX 6. Howtheapptranspilingworks 7. ThedynamicnatureofJSX 0.2.3 Things covered in Chapter 3: Build React apps locally without webpack Inthischapter,I’veshowntoyouthefollowing: 1. Amorein-depthlookatReact.createElement 2. UnderstandingclassName 0.2.4 Things covered in Chapter 4: What is JSX Inthischapter,I’veguidedyouthrough: 1. StructuringthereturnvaluesusingJSX 2. WorkingwithBabel 3. Usingdynamic(evaluated)valuesinJSX 4. WorkingwithnestedelementsinJSX 0.2.5 Things covered in Chapter 5: Components and props Inthischapter,we’velearned: 1. HowtocodeacomponentinReact 2. Howtoexportacomponentandhowtoimportitintoanothercomponent 3. Usingasinglewrappingelementisamust 4. IntroductiontopropsinReact 5. Parent-childstructureofcomponentsinReact 0.2.6 Things covered in Chapter 6: Assets in React Inthischapter,I’veshowntoyouhowtouseimagesandJSONinReactapps,andhowtoloopover theJSONdatainsideacomponent. Chapter0: Beforewestart 4 0.2.7 Things covered in Chapter 7: JSX and styling Inthischapter,I’veshowntoyouhowtoworkwithstylesinJSX.Specifically,I’vecovered: 1. Importingstylesusingthelinkelement 2. Inlinestyleswithobjectliterals 3. Inlinestyleswithvariables 4. Composablestylesusingthespreadoperator 0.2.8 Things covered in Chapter 8: Build a static Bootstrap layout Inthischapter,I’veshowntoyouhowtousetheBootstrapframeworkwithReact,withoutusinga custom-madeframeworklike,forexample,React-Bootstrap. I’vealsoshownhowtoworkwiththechildrenprop. 0.2.9 Things covered in Chapter 9: Looping over data Inthischapter,I’veexplainedthetopicofloopingoverdata.I’veshownyouapracticalexampleof mappingoverdataandforeachpieceofdata,renderingacomponent.Thatway,youavoidrepetition andmakeyourcodeeasiertoreasonabout. I’vealsoshowntoyouhowtorefactoracomponentsothat: • itusesasingleprop,and • usesobjectdestructuring 0.2.10 Things covered in Chapter 10: The very basics of data and events in React Inthischapter,I’vecoveredthefollowing: 1. Data 2. Statedata 3. Usingeventstoupdatestatedata Chapter0: Beforewestart 5 0.2.11 Things covered in Chapter 11: Conditional rendering Inthischapter,I’veshownyouhowtoconditionallyrender: 1. if-elsestatements 2. classNamesusingternaryoperators 3. adifferentvaluethantheoneinreceivedinthepropsobject 4. differentcomponents 5. componentsusingthe&&operator I’vealsoshowntoyouhowto: • extractthereturnvaluesasvaraibles • renderingthemusingtheternaryoperator 0.3 What this book is about? Ok,sonowthatIhavegivenyouanoverviewofthingscoveredinthepreviousbook,I’dliketogive youaquickintroductiontothingsthatthisbookwillbediscussing. First of all, since the title of this book series is “React from Scratch”, I’m indeed working on introducingyoutoalltherelevant,importantconcepts,withoutthelearningcurvebeingtoosteep. What that means is that, now you understand the very basics of React’s syntax and some of the logic behind it, I’ll continue with the approach from the previous book: introducing a new concept, isolatingitandsimplifyingitasmuchaspossible,andthengivingyouanappthatshowshowthat conceptworksinpractice. Thisshouldhelpyoubeconfidentinbuildingyourowncodethat’ssimilartotheoneshown. Furthermore, this approach will allow us to build “multi-page” SPAs in the book that follows this one. However,weshouldn’tgetaheadofourselves.Fornow,thefocusisonunderstandinghooks,forms, and some related concepts, without which it will be quite difficult to make some more advanced Reactapps. WelcometoBook2:HooksandForms. Chapter 1: Understanding the useState hook 1.1 Updating a component’s state using the useState hook Ideally,anappwouldconsistofstatelesscomponentsthroughandthrough. Inotherwords,anidealappwouldbeastaticapp,wherecomponentscomposetogethertobuildan appthathasnostate. However,thatappwouldbeboring.Auserwouldnotbeabletointeractwithitotherthanreadthe informationonthescreen-sincethatinformationwouldneverchange. Thismeansthatalotofinteractivityinanappisactuallyuser-triggered. Forexample,ifIwanttoallowausertoaddanitemtoacartonashoppingwebsite,I’llhaveto: • addabuttonfortheusertopresstocompletesuchanaction • reacttoeventstriggeredbysuchauseraction Essentially, what this boils down to is that we need to code our React apps to handle user events whichwillinturnupdateagivencomponent’sstate. ThatmeansthatIneedto: 1. Setupstateinacomponent 2. Setupeventhandlers 3. Updatestateinsideeventhandlers Inthefirstbookofthisbookseries,I’veshowntoyouabasicexampleofhowthisisdone. Asastartingpoint,here’saquickreminder,Abasicadd-to-cartexample,pt3*. Theentireappwasjustasinglecomponent -theApp component: *https://codesandbox.io/s/a-basic-add-to-cart-example-pt-3-hqq0fr