How to Integrate Bootstrap with ReactJS | Pluralsight

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

At this stage, the library will not work as expected since it does not include Bootstrap CSS. We'll need to add it manually as shown below:. ChrisParkerHowtoIntegrateBootstrapwithReactJSChrisParkerJan10,202016Minread61,945ViewsJan10,202016Minread61,945ViewsWebDevelopmentReactIntroduction143IntroductionWhyBootstrapComponentsCannotBeIncludedwithReactHowtoSetupBootstrapStylesheetwithReactHowtoUseRegularBootstrapClassesWithReactUsingThird-partyLibrariesforReactandBootstrapHowtoSetUpReactstrapLibraryUnderstandingBootstrapGridUsingBootstrapComponentsWithReactConclusionTopIntroductionWe'llfocusonthefollowingskillsinthisguide:BuildingUIinaReact-basedwebappandusingBootstrap'slookandfeel.UsingreactstraptodevelopaReactappforlistingcontacts.ReactisthemostcommonlyusedJSframeworkfordevelopinginteractivewebapps. Butsinceitisaviewlibrary,itdoesnotcomewithtechniquestobuilddesignsthatareresponsiveandveryintuitive.Inordertoovercomethis,wecanuseBootstrap,whichisafront-enddesignframework.WhyBootstrapComponentsCannotBeIncludedwithReactAddingaHTMLtagliketoanHTMLfilelikeindex.htmlisaneasytask,butit’snotthesamewhenaddingBootstraptoReact.ThereasonisthatBootstrapreliesonjQuerytorunparticularuserinterfacecomponents.AndjQuerymanipulatestheDOMdirectly,whichcontradictsthedeclarativeapproachofReact. WecanusethesimplevanillaBootstrapstylesheetforwebapplicationsiftherequirementislimitedtoareceptive12-columngridorcomponentsthatdonotinvolvejQuery.Otherwise,therearedifferentlibrariesthatcanenabletheuseofBootstrapalongwithReact.We'llexaminebothmethodssothatwecanchoosewhichoneisbestsuitedforagivenscenario. We'llfocusontheimplementationdetailsforintegratingBootstrapwithReactapp.HowtoSetupBootstrapStylesheetwithReactWewillbeusingCreateReactAppCLItogetstartedwithourReactproject.Itdoesnotrequireanyconfigurationtostart.ThefollowingcommandscanbeusedinstallCreateReactAppandtostarttheserverindevelopmentmode:1$create-react-appmy-bootstrap-react-app 2$cdmy-bootstrap-react-app 3$npmstart javascriptThedirectorystructuregeneratedbyCreateReactAppisasbelow:1. 2├──package.json 3├──public 4│├──favicon.ico 5│├──index.html 6│└──manifest.json 7├──README.md 8├──src 9│├──App.css 10│├──App.js 11│├──App.test.js 12│├──index.css 13│├──index.js 14│├──logo.svg 15│└──registerServiceWorker.js 16└──yarn.lockjavascriptThenextstepistotakethelatestBootstraplibraryfromitsofficialwebsite.ThedownloadedpackageconsistsofthecompiledaswellasminimizedversionsofJavaScriptandCSSfiles.Thereisagrid-specificstylesheetaswellforappsthatjustneedtomakeuseofgrids. ThenextstepistomakeanewfolderforCSSinpublic,copybootstrap.min.cssfilethere,andthenaddtherequiredcodeinpublic/index.htmltolinkit.1

2 3htmlAnotherwayistouseaCDNtofetchtheminimizedCSS:1htmlHowtoUseRegularBootstrapClassesWithReactWecanuseBootstrapclasseswithJSXcodeaftertheBootstrapstylesheethasbeenaddedtoaReactapp.Inordertoverifythis,we'llcopysomerandomsamplecodefromtheBootstrapdemosite:1importReactfrom"react"; 2import{render}from"react-dom"; 3importFormsfrom"./Forms"; 4importNavBarfrom"./NavBar"; 5 6constApp=()=>( 7
8 9
10 11 12 13 14
15 16 17 18); 19 20render(,document.getElementById("root"));javascriptItwouldbereallyniceiftheBootstrapclassescouldbeimportedasReactcomponentstomakethebestuseofReact.Forexample,wecouldhavegrid,rowandCcolumncomponentstoorganizethepageinsteadoftheHTMLclassesasshownbelow:1 2 3 4 5 6Col1of3 7 8 9Col2of3 10 11 12Col3of3 13 14 15 16 17 18 19 20 21 22Col1of3 23 24 25Col2of3 26 27 28Col3of3 29 30 31htmlLuckily,thereisnoneedtoimplementourownlibrarytomakethispossible,astherearelibrariesalreadyavailable.Let’sexploreafewofthese.UsingThird-partyLibrariesforReactandBootstrapTherearesomelibrariesthatattempttodevelopanimplementationofBootstrapthatisspecifictoReactthatwillallowustouseJSXcomponentsaswellasworkwithBootstrapstyles. FollowingaresomeofthepopularBootstrapmodulesthatcanbeusedwithReactprojects.React-BootstrapisamongstthetoplibrariesforaddingBootstrapcomponentstoReactprojects.ButitscurrentimplementationistargetedforBootstrapv3andnotthelatestversion.reactstrapisanotherlibrarywhichenablesustouseBootstrapcomponentsinaReactapp.IncontrasttoReact-Bootstrap,reactstrapisdevelopedtobeusedwiththelatestversionofBootstrap.Thereactstrapimplementationhascomponentsforforms,buttons,tables,layoutgrids,andnavigation.Itiscurrentlyindevelopment,butprovidesanicealternativefordevelopingappswithReactandBootstraptogether.TherearesomealternativeslikeReact-UIandsomedomain-specificmoduleslikeCoreUI-React,React-bootstrap-tableavailableonGitHubthatdeliverextensiveutilitiestodevelopsomecoolUIforappsusingReact.Inthisguide,we'llfocusonreactstrapsinceitisthemostpopularandusesthelatestBootstrapversion.HowtoSetUpReactstrapLibraryTogetstarted,weinstallthereactstraplibraryusingnpm:1npminstall--save[email protected]javascriptNow,therelevantcomponentsfromthemodulecanbeimportedasbelow:1import{Container,Row,Col}from'reactstrap';javascriptAtthisstage,thelibrarywillnotworkasexpectedsinceitdoesnotincludeBootstrapCSS.We'llneedtoadditmanuallyasshownbelow:1npminstall--savebootstrapjavascriptNextstepistoimportBootstrapCSSinoursrc/index.jsfile:1import'bootstrap/dist/css/bootstrap.css';javascriptUnderstandingBootstrapGridBootstrapisdevelopedwitharesponsive,mobilefirstgridsystemthatenablestheuseof12columnsperpage.We'llneedtoimporttheContainer,RowandColcomponentsinordertousethegrid. TheContainerhasafluidattributethataltersafixed-widthlayouttoafull-widthlayout.Itessentiallyaddsthe.container-fluidbootstrapclasstothegrid. TheColcomponentcanbeconfiguredtoworkwithattributeslikexs,md,smandlgthatworkthesamewayasthecol-*classesinBootstrap,e.g.,. Anotherwaytoimplementthisisbypassinganobjecttothepropswithoptionalattributeslikesize,order,andoffset.Thesizeattributedenoteshowmanycolumnsarethereinthegrid,whileorderenablesustoarrangethecolumnsandworkswithvaluesfrom1to12.Thecolumnscanbemovedtotherightbyusingtheoffsetproperty. ThefollowingcodeelaboratesafewofthefeaturesofGridinreactstrap:1importReact,{Component}from"react"; 2import{render}from"react-dom"; 3import{Row,Col,Container}from"reactstrap"; 4import"bootstrap/dist/css/bootstrap.css"; 5import"./App.css"; 6 7classAppextendsComponent{ 8render(){ 9return( 10
11 12 13 14.col 15 16 17 18 19.col-4 20 21 22 23.col-4 24 25 26 27 28 29.col-6 30 31 32 33.col-6 34 35 36.col-6 37 38 39 40 41.col 42 43 44.col 45 46 47.col 48 49 50.col 51 52 53 54 55.col-3 56 57 58.col-autoisusedfordynamiccontent 59 60 61.col-3 62 63 64 65 66.col-sm-4.col-sm-order-4.col-sm-offset-4{""} 67 68 69 70 71.col-sm-10.col-md-4.col-md-offset-5 72 73 74 75
76); 77} 78} 79 80exportdefaultApp; 81constBox=props=>{props.children}; 82render(,document.getElementById("root"));javascriptUsingBootstrapComponentsWithReactNowthatwearefamiliarwithreactstrapandhowitworks,therearenumerouscomponentsofBootstrap4thatcanbeusedwithReactusingreactstrap.We'lllookatfewoftheimportantcomponentsinthisguide.NavigationBarreactstrapNavbarscanbeusedfornavigationbarsandprovideresponsiveness.Toorganizethenavigationlinksmoreefficiently,aNavbarconsistsofsubcomponentslikeNav,NavItem,NavbarBrand,etc . AresponsiveNavbarcancreatedbyaddingainsideourcomponentandthenwrappingintoacomponent. We'lllookatthefollowingcodetoseehowtheNavbarcomponentandReactstatecanbeusedtosavethetoggledata;:1exportdefaultclassNavBarExampleextendsReact.Component{ 2constructor(props){ 3super(props); 4this.toggleOpenState=this.toggleOpenState.bind(this); 5this.state={ 6isOpen:false 7}; 8} 9toggleOpenState(){ 10this.setState({ 11isOpen:!this.state.isOpen 12}); 13} 14render(){ 15return( 16
17 18 19ThisisaNavbarDemo 20 21{/*Below,we'lladdtogglerforauto-collapse*/} 22 23 24 25{/*Pulltowardsleft*/} 26 27 28 29LeftNavigationLink 30 31 32 33 34{/*Pulltowardsright*/} 35 36 37 38Chris 39 40 41 42MyAccount 43 44 45PageSettings 46 47 48 49LogOut 50 51 52 53 54 55 56
57); 58} 59}javascriptModalWindowThereactstrapModalcomponentcanbeusedforgeneratingaBootstrapmodalwithaheader,body,andfooter. Amodalcomponentcanbeusedwithsomepropsandcallbackstohavethewindowinteractiveandalsotohaveitclosable. Todecidewhetherthemodalshouldbevisibleornot,theisOpenpropertyisused.ThetogglecallbackisusedtoswitchthevalueofisOpeninthecomponent. Therearefewmorepropsthatareusedtoanimatethetransitions.TheavailablecallbacksincludeonEnter,onExit,onOpened,andonClosed:1{/*Toopenthemodalwindow,this.state.showneedstobetrue,whichisgenerallysetbyan"onClick"event*/} 2{/*toggleModalupdatesstateof"show"tofalseonClose*/} 3 4 5 6 7Modaltitle 8 9 10 11Loremipsumdolorsitamet,consecteturadipiscingelit.Sedullamcorpertristiquesuscipit.Inultricessagittisiaculis.Maecenasporttitorelitegetnequemolestie,idsodalesdiamconsectetur.Fuscecursusjustoquiseroscommodopellentesque.AeneanegetegestasaugueVivamussitametrhoncuslorem,velpulvinartellus. 12 13 14ClickonMe!{''} 15Cancel 16 17htmlFormsAreactstrapformcanbeinlineorhorizontal.TheinputelementisrenderedbyanInputcomponent.MultipleInputcomponentscanbewrappedintoaFormGroupforstatevalidation,appropriatespacing,andtouseotherFormGroupfeatures. Tosetanylabel,wecandothatusing 4 5 6 7 8 9 10Password 11 12 13 14 15 16 17Select 18 19 20 21 22 23 24SelectMultiple 25 26 27 28 29 30 31TextArea 32 33 34 35 36htmlListGroupThestylingandcontroloflistitemscanbedoneeasilyusingreactstrapListGroup.TheListGroupItemsarewrappedinListGroup.TheonClickcallbackcanbeusedtomakeitinteractive. BelowisthecodeforListGroup;1 2Item1 3Item2 4... 5;htmlButtonsButtonscanbethemostimportantcomponentforanydesignframework.ThereisareactstrapButtoncomponentforbuttons.Otherthanthegeneralactiveanddisabledproperties,wecanusecolorandsizetosetthestyle(primary,success,etc.)andsize(lg,sm,etc.)ofbuttons:1{/*ButtonToolbarhelpstoorganizebuttons*/} 2
3Primarybtn{''} 4Secondarybtn{''} 5Warningbtn{''} 6Dangerbtn{''} 7 Successbtn{''} 8infobtn{''} 9linkbtn 10
htmlConclusionEverythingthatweneedtointegrateBootstrapwithReactapphasbeencoveredinthisguide. TherearenumerouslibrariestointegrateBootstrapwithReactappandwehavediscussedfewofthebestknownones.Wehavealsoworkedwithoneofthemostcommonlyusedlibraries,reactstrap.143LEARNMORE


請為這篇文章評分?