How to Use Bootstrap Components with React.js | Pluralsight

文章推薦指數: 80 %
投票人數:10人

A solution to the above-mentioned problems is using React Bootstrap, a component-based library where everything is essentially a React ... GauravSinghalHowtoUseBootstrapComponentswithReact.jsGauravSinghalMay28,202012Minread10,956ViewsMay28,202012Minread10,956ViewsWebDevelopmentFrontEndWebDevelopmentClient-sideFrameworkReactIntroduction33IntroductionBootstrapComponentsUsingNativeBootstrapwithReactDisadvantagesofNativeBootstrapUsingReactBootstrapConclusionTopIntroductionReact'ssupportforaplethoraofframeworksandlibrarieshasalloweddeveloperstobuildintriguingUIwithminimalcodeandintegrateexternalAPIsforintricatefunctionalities.BootstrapisthemostpopularCSSframework,usedbyamultitudeofenterprisesforsingle-pageapps,andit'seasytouseinReact.ThisguideexploreshowtouseBootstrapcomponentswithReactjsinprimarilytwoways:directlyusingnativebootstrapcomponentsandusingitscomponent-basedlibrary,ReactBootstrap.BootstrapComponentsBootstrapoffersavarietyofcomponentsthatcanbeusedinyourmarkuptemplatestoofferaseamlessuserexperiencethroughoutyourapp.Someoftheseinclude:Alertsandtoastsforanevent'sfeedbackModals,tooltips,collapsible,andpopoversfordisplayingadditionalinformationForms,dropdowns,inputgroups,andselecttohandleuserformsButtons,progress,andspinnerstoenhancethevisualeffectsoftheappLists,pagination,andbreadcrumbsfordisplayinglargeamountsofcontentinapresentableformatBadges,cards,carousel,andjumbotronsforanattractiveUIThisguideputsmoreemphasisontheimplementationpatternsothesameknowledgecanbeextendedtoanyBootstrapcomponentinReact.UsingNativeBootstrapwithReactStartbycreatinganemptyproject.MakesureyouhaveNodejsandnpminstalledinyourmachine(atleastversion8orhigher)alongwithacodeeditorandawebbrowser(preferablyChromeorFirefox).Createanewprojectusingcreate-react-app:1npxcreate-react-appbootstrap-reactshellCleaninguptheTemplateRemovethelogo,App.css,andalltheirimportsfromApp.js.CleanoutthestartertemplateinsidetheAppcomponent.YourApp.jsshouldlooklike this:1importReactfrom'react'; 2 3functionApp(){ 4return( 5 6

Hello

7 8); 9} 10 11exportdefaultApp;jsxSettingupBootstrapFirstyouneedtogettheBootstrapstyles.Headovertohteindex.htmlfileinsidethepublicfolderandaddthefollowingCDNinsidethe :1... 2 3... htmlNowalltheBootstrapstyleclassesarereadytobeusedwithJSXelements.AddthefollowingscripttagstoenableJavaScriptofthecomponents .1... 2 3 4 5 6 7... htmlTomakesuretheHTMLbodyloadsbeforeloadingthesescripts,putthemrightabovetheclosingofyourindex.html.UsingAlerts,ButtonsandFormComponentsTocreateasimpleformusingBootstrap'sformcomponent,addthefollowingcodeinsideApp.js .1importReactfrom'react'; 2 3functionApp(){ 4return( 5 6 7
8 9 10 12
13 14 15); 16} 17 18exportdefaultApp;jsxThiswillrendertheformonthepagewithaninputfieldandabutton.ThesecomponentscanbeusedbysimplyputtingdowntheirmarkupinyourJSXtemplate.However,togetthesecomponentsinanevent-drivenformat,yourparentcomponentshouldinteractwiththemthroughthestate.ImporttheuseStatehookandcreateastatevariabletokeeptrackofanalertthatwilltriggerwhenthisformgetssubmitted.Setitinitiallyfalse.1importReact,{useState}from'react'; 2 3functionApp(){ 4let[alert,setAlert]=useState(false); 5... 6}jsxAddasubmiteventthatfiresupwhentheformsubmitstosetthealert'svaluetotrue.1importReact,{useState}from'react'; 2 3functionApp(){ 4let[alert,setAlert]=useState(false); 5 6consthandleSubmit=(e)=>{ 7e.preventDefault(); 8setAlert(true); 9} 10 11return( 12 13 14 15... 16) 17} jsxLast,conditionallyoutputaBootstrapalertcomponentasaJSXelement.1... 2{alert&& 3Congrats!Yourdetailshavebeensubmittedsuccessfully 4{setAlert(false)}}> 6× 7 8 9} 10...jsxNotethatyouneedtosetthevalueofthealertbacktofalseafteritisdismissedsothestatevariablesstayinlinewiththealertevent.Theinlinefunctionontheclosingbuttondoesthisjob.TestingInsidetherootdirectory,run thefollowing.1npmstartThiswillspinupalocaldevelopmentserver(usuallyonport3000)andyoucanseeyourformalongwithabuttononthepage.Clickthesubmitbuttonandanalertwithasuccessmessageappearsonthepage.Youcanclosethealertandfireitagainthroughthesubmitbutton.DisadvantagesofNativeBootstrapUsingnativebootstrapseemssimpleandconvenient,butthereareafewdisadvantagesassociatedwithit. Theseinclude:UnnecessarilylongJSX,mitigatingreadabilityLessmodularity,makingitdifficulttodebugCustomizingcomponentsmightrequireexternalJavaScriptorJQueryUpgradingtonewerversionsrequiresmanuallyupdatingalltheCDNsandcheckingthecodefordepreciatedclassesandelementsLackofcomponentarchitectureUsingReactBootstrapAsolutiontotheabove-mentionedproblemsisusingReactBootstrap,acomponent-basedlibrarywhereeverythingisessentiallyaReactcomponentthatcanberenderedasachildcomponentinsidethecomponentoutputtingit.SetupYoucancreateafreshCRAprojectbyfollowingtheearlierstepsupuntilthe'SettingupBootstrap'section,oryoucancleanouttheearliertemplatebyundoingeverythingbacktothe'SettingupBootstrap'section.YourcleanandemptyApp.jsisgoodtogo.InstallingReactBootstrapInsidetherootdirectory,runthefollowingcommandtoinstalltheReactBootstraplibrary .1npminstallreact-bootstrapbootstrapThiswillinstallbothBootstrapandReactBootstrapinsidetheproject.UsingtheDropdownComponentForregularBootstrapstylestoworkcorrectly,importtheBootstrapstylesontop.YouneedtodothiseverytimeyouuseaReactBootstrapcomponent.1import'bootstrap/dist/css/bootstrap.min.css';jsxTheaboveisequivalenttoaddingBootstrapCDNinyourindex.htmlfile.NowimporttheDropdownButtonandDropdownfromreact-bootstrap.Thisstepiscommonregardlessofthecomponentyou'reusing,butmakesureyou'reimportingtherightandonlyrequiredcomponents.1importDropdownButtonfrom'react-bootstrap/DropdownButton'; 2importDropdownfrom'react-bootstrap/Dropdown'jsxRenderthemontheDOMinsideApp.js .1importReactfrom'react'; 2import'bootstrap/dist/css/bootstrap.min.css'; 3importDropdownButtonfrom'react-bootstrap/DropdownButton'; 4importDropdownfrom'react-bootstrap/Dropdown' 5 6functionApp(){ 7return( 8 9 14option-1 15option-2 16option3 17 18somelink 19 20 21); 22} 23 24exportdefaultApp;jsxYoucanseeyourDropdownComponentrenderedwithalistofitems.Let'slookatanotherexample .UsingthePopoverComponentsInsideacleanandemptyApp.js,afterimportingBootstrapstyles,importPopover,OverlayTrigger,andButtonfromreact-bootstrap .1importPopoverfrom'react-bootstrap/Popover'; 2importOverlayTriggerfrom'react-bootstrap/OverlayTrigger'; 3importButtonfrom'react-bootstrap/Button';jsxTocreateapopoverinsidethepopovercomponent,renderthePopover.TitlecomponenttoindicatethetitleofthepopoverandPopover.Contentcomponenttoindicateitscontent.StorethispopoverinaconstantvariableandoutputitinsidetheJSXtemplate.1... 2constpopover=( 3 4Popovertitle 5 6PopovercontentsomestrongcontentNormalcontentagain 7 8 9); 10...jsxOutputthepopoverinsideanoverlayandusethetriggerproptosetthetypeofeventtheoverlaylistensfor.Theplacementpropdefinesthepositionofyourpopover.1.... 2return( 3 4 5Clicktotriggerpopover 6 7 8); 9....jsxFinally,yourApp.jsshouldlooklikethis :1importReactfrom'react'; 2import'bootstrap/dist/css/bootstrap.min.css'; 3importPopoverfrom'react-bootstrap/Popover'; 4importOverlayTriggerfrom'react-bootstrap/OverlayTrigger'; 5importButtonfrom'react-bootstrap/Button'; 6 7functionApp(){ 8constpopover=( 9 10Popovertitle 11 12PopovercontentsomestrongcontentNormalcontentagain 13 14 15); 16 17return( 18 19 20Clicktotriggerpopover 21 22 23); 24} 25 26exportdefaultApp;jsxNowyoucanseethepopoverbuttonandthepopoveritselfwhenyouclickonthebutton.Incaseyougetanydepreciatedwarningsorerrors,youcanusetheexactversionofreact-bootstrapthatisusedinthisguidebyupdatingyourpackage.jsonfileandrunningthecommandnpmi .1.... 2"bootstrap":"^4.4.1", 3"react-bootstrap":"^1.0.1", 4.... jsonConclusionBothmethodsdiscussedinthisguideletyouusebootstrapcomponentsinyourReactproject,allowingyoutodevelopyourappfasterwithoutcompromisingtheUI/UX.Choosethefirstoneforsmallerapplications,asthefewerdependenciesyourprojecthas,thesmootheritruns.However,makesureyou'rekeepingthecodeasmodularasyoucan.Forlargeapplications,usingReactBootstrapisanidealchoice.33LEARNMORE



請為這篇文章評分?