Using Bootstrap with React - LogRocket Blog

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

You can use Bootstrap directly on elements and components in your React app by applying the built-in classes just like any other class. Let's ... Share Reply 4 GladChindaFollow Full-stackwebdeveloperlearningnewhacksonedayatatime.Webtechnologyenthusiast.Hackingstuffs@theflutterwave. UsingBootstrapwithReact October12,2020 15minread 4219 Theincreasingpopularityofsingle-pageapplicationsoverthelastfewyearshasledtoaninfluxofJavaScriptframeworks,includingAngular,React,Vue.js,Ember—thelistgoeson.Asaresult,it’snolongernecessarytouseaDOMlibrary,suchasjQuery,tobuildwebapps. ThishascoincidedwiththeemergenceofCSSframeworksdesignedtohelpdevelopersbuildresponsivewebapps.Ifyou’reafrontenddeveloper,you’vealmostcertainlyusedoratleastheardaboutBootstrap,Foundation,andBulma,allresponsive(mobile-first)CSSframeworkswithrobustfeaturesandbuilt-inutilities.IfReactisthemost-usedJavaScriptframeworkforbuildingwebapplications,BootstrapisthemostpopularCSSframework,poweringmillionsofwebsitesontheinternet. Inthistutorial,we’llshowyouhowtouseReactandBootstrap,howtoaddBootstraptoaReactapp,howtoinstallReactBootstrappackagessuchasreact-bootstrap(withexamples),and,finally,howtocreateaReactappwithBootstrap. Ifyou’rejustgettingstartedwiththeseframeworks,I’dsuggestskimmingthroughtheofficialReact andBootstrapdocumentation.I’dalsoencourageyoutowatchthecomprehensivevideotutorialbelowforadeeperdive. AddBootstraptoReact ThethreemostcommonwaystoaddBootstraptoyourReactappare: UseBootstrapCDN ImportBootstrapinReactasadependency InstallaReactBootstrappackage(suchasbootstrap-reactorreactstrap) 1.UsingBootstrapCDN BootstrapCDNistheeasiestwaytoaddBootstraptoyourReactapp.Noinstallsordownloadsrequired.Simplyputaintothe

sectionofyourapp,asshowninthefollowingsnippet. IfyouareinterestedinusingtheJavaScriptcomponentsthatshipwithBootstrap,youneedtoplacethefollowing Asyoucansee,Bootstrap4requiresjQueryandPopper.jsforitsJavaScriptcomponents.Intheabovesnippet,weusedjQuery’sslimversion,althoughyoucanusethefullversionaswell. ForyourReactapp,thesecodesnippetswillusuallybeaddedtotheindexpageofyourapp.Ifyouusedcreate-react-apptocreateyourapp,thenyourpublic/index.htmlpageshouldlooklikethefollowingsnippet: Wemadeacustomdemofor.Noreally.Clickheretocheckitout. Clickheretoseethefulldemowithnetworkrequests ReactApp Nowyoucanstartusingthebuilt-inBootstrapclassesandJavaScriptcomponentsinyourReactappcomponents. 2.ImportBootstrapasadependency Ifyouareusingabuildtooloramodulebundlersuchaswebpack,thenthisisthepreferredoptionforaddingBootstraptoyourReactapplication.YouwillneedtoinstallBootstrapasadependencyforyourapp. npminstallbootstrap OrifyouareusingYarn: yarnaddbootstrap OnceyouhaveBootstrapinstalled,goaheadandincludeitinyourapp’sentryJavaScriptfile.Ifyouareusedtocreate-react-app,thisshouldbeyoursrc/index.jsfile. import'bootstrap/dist/css/bootstrap.min.css'; importReactfrom'react'; importReactDOMfrom'react-dom'; import'./index.css'; importAppfrom'./App'; importregisterServiceWorkerfrom'./registerServiceWorker'; ReactDOM.render(,document.getElementById('root')); registerServiceWorker(); NoticethatwehaveimportedtheBootstrapminifiedCSSasthefirstdependency.Withthis,wecangoaheadusingthebuilt-inBootstrapclassesinourReactappcomponents.However,beforeyoucanuseBootstrap’sJavaScriptcomponentsinyourapp,you’llneedtoinstalljqueryandpopper.jsiftheyarenotalreadyinstalled. npminstalljquerypopper.js Next,youwillmakeadditionalchangestothesrc/index.jsfiletoaddthenewdependenciesasshowninthefollowingsnippet. import'bootstrap/dist/css/bootstrap.min.css'; import$from'jquery'; importPopperfrom'popper.js'; import'bootstrap/dist/js/bootstrap.bundle.min'; importReactfrom'react'; importReactDOMfrom'react-dom'; import'./index.css'; importAppfrom'./App'; importregisterServiceWorkerfrom'./registerServiceWorker'; ReactDOM.render(,document.getElementById('root')); registerServiceWorker(); Hereweaddedimportsfor$andPopper.WealsoimportedtheBootstrapJavaScriptminifiedbundlefile.NowyoucanuseBootstrapJavaScriptcomponentsinyourReactapp. 3.InstallaReactBootstrappackage ThethirdwaytoaddBootstraptoaReactappistouseapackagethathasrebuiltBootstrapcomponentsdesignedtoworkasReactcomponents.Thetwomostpopularpackagesare: react-bootstrap reactstrap BothpackagesaregreatchoicesforusingBootstrapwithReactappsalthoughyouarenotnecessarilyrequiredtouseanyofthem.Theyshareverysimilarcharacteristics. Usingbuilt-inBootstrapclassesandcomponents YoucanuseBootstrapdirectlyonelementsandcomponentsinyourReactappbyapplyingthebuilt-inclassesjustlikeanyotherclass.Let’sbuildasimplethemeswitcherReactcomponenttodemonstrateusingBootstrapclassesandcomponents. ThemeSwitcher Demo Asshowninthisdemo,weareusingadropdowncomponentavailableinBootstraptoimplementourthemeswitcher.Wealsousethebuilt-inbuttonclassestosetthesizeandcolorofthedropdownbutton. WewillgoaheadtowritethecodeforourThemeSwitchercomponent.EnsureyouhaveaReactapplicationalreadysetup.Createanewfileforthecomponentandaddthefollowingcodesnippettoit: importReact,{Component}from'react'; classThemeSwitcherextendsComponent{ state={theme:null} resetTheme=evt=>{ evt.preventDefault(); this.setState({theme:null}); } chooseTheme=(theme,evt)=>{ evt.preventDefault(); this.setState({theme}); } render(){ const{theme}=this.state; constthemeClass=theme?theme.toLowerCase():'secondary'; return( {theme||'Default'} {theme||'Choose'}Theme ToggleThemeDropdown this.chooseTheme('Primary',e)}>PrimaryTheme this.chooseTheme('Danger',e)}>DangerTheme this.chooseTheme('Success',e)}>SuccessTheme DefaultTheme ); } } exportdefaultThemeSwitcher; HerewehavebuiltaverysimplethemeswitchercomponentleveragingonBootstrap’sdropdowncomponentandacoupleofbuilt-inclasses.YoucanlearnmoreaboutusingBootstrapdropdownhere. First,wesetupthecomponent’sstatewithathemepropertyandinitializedittonull.Next,wedefinedtwoclickeventhandlersresetTheme()andchooseTheme()onthecomponentclassforchoosingathemeandresettingthethemerespectively. Intherender()method,werenderasplitbuttondropdownmenucontainingthreethemes.namely:Primary,Danger,andSuccess.Eachmenuitemisattachedtoaclickeventhandlerfortheappropriateaction.Noticehowweusetheme.toLowerCase()togetthethemecolorclassforboththedropdownbuttonsandthetext.Wedefaulttousingsecondaryasthethemecolorifnothemeisset. Inthisexample,wehaveseenhoweasyitistouseBootstrap’sbuilt-inclassesandcomponentsinourReactapp.ChecktheBootstrapdocumentationtolearnmoreaboutthebuilt-inclassesandcomponents. react-bootstrapexample Now,wewillrebuildourthemeswitcherusingreact-bootstrap.Wewillusethecreate-react-appcommand-linetooltocreateourapp.Ensurethatyouhavethecreate-react-apptoolinstalledonyourmachine. CreateanewReactappusingcreate-react-appasfollows: create-react-appreact-bootstrap-app Next,goaheadandinstallthedependenciesasfollows: yarnadd[email protected]react-bootstrap react-bootstrapcurrentlytargetsBootstrapv3.However,workisactivelyongoingtoprovideBootstrapv4support. CreateanewfilenamedThemeSwitcher.jsinthesrcdirectoryofyourprojectandputthefollowingcontentinit. importReact,{Component}from'react'; import{SplitButton,MenuItem}from'react-bootstrap'; classThemeSwitcherextendsComponent{ state={theme:null} chooseTheme=(theme,evt)=>{ evt.preventDefault(); if(theme.toLowerCase()==='reset'){theme=null} this.setState({theme}); } render(){ const{theme}=this.state; constthemeClass=theme?theme.toLowerCase():'default'; constparentContainerStyles={ position:'absolute', height:'100%', width:'100%', display:'table' }; constsubContainerStyles={ position:'relative', height:'100%', width:'100%', display:'table-cell', verticalAlign:'middle' }; return( {theme||'Default'} PrimaryTheme DangerTheme SuccessTheme DefaultTheme ); } } exportdefaultThemeSwitcher; Herewehavetriedtomimicourinitialexampleasmuchaspossibleusingreact-bootstrap.Weimporttwocomponentsfromthereact-bootstrappackage,namelySplitButtonandMenuItem.Seethereact-bootstrapDropdowndocumentationtolearnmore. First,wesetupthecomponent’sstatewithathemepropertyandinitializedittonull.Next,wedefineachooseTheme()clickeventhandlerforchoosingathemeorresettingthetheme. SinceweareusingBootstrap3.3.7,wecreatedsomecontainerstylesintherender()methodtohelpusachievehorizontalandverticalcentering. NoticehowwespecifythebuttonsizeontheSplitButtoncomponentusingthebsSizeprop.Also,noticehowwearepassingthethemeClasstothebsStyleproptodynamicallychangethebuttoncolorbasedonthestate’stheme. WepassthethemenametotheeventKeypropofeachMenuItemcomponent.WealsosettheonSelecthandlertothis.chooseTheme(),whichwedefinedearlier.TheMenuItemcomponentpassestheeventKeyandtheeventitselftotheonSelecthandlerasfollows: (eventKey:any,event:Object)=>any Finally,wewillmodifythesrc/index.jsfiletolooklikethefollowingsnippet: import'bootstrap/dist/css/bootstrap.min.css'; import'bootstrap/dist/css/bootstrap-theme.min.css'; importReactfrom'react'; importReactDOMfrom'react-dom'; import'./index.css'; importAppfrom'./App'; importThemeSwitcherfrom'./ThemeSwitcher'; importregisterServiceWorkerfrom'./registerServiceWorker'; ReactDOM.render(,document.getElementById('root')); registerServiceWorker(); Here,wefirstimportBootstrap’sminifiedCSSfiles.WealsoimportourThemeSwitchercomponentandrenderittotheDOM. Ifyouruntheappnowwiththecommandyarnstartornpmstart.Yourappshouldstartonport3000andshouldlooklikethefollowingdemo: react-bootstrapdemo. reactstrapexample Wewillgoaheadandrebuildourthemeswitcherusingreactstrapthistime.Wewillusethecreate-react-appcommand-linetooltocreateourapp.Ensurethatyouhavethecreate-react-apptoolinstalledonyourmachine. CreateanewReactappusingcreate-react-appasfollows: create-react-appreactstrap-app Next,goaheadandinstallthedependenciesasfollows: yarnaddbootstrapreactstra CreateanewfilenamedThemeSwitcher.jsinthesrcdirectoryofyourprojectandputthefollowingcontentinit: importReact,{Component}from'react'; import{Button,ButtonDropdown,DropdownToggle,DropdownMenu,DropdownItem}from'reactstrap'; classThemeSwitcherextendsComponent{ state={theme:null,dropdownOpen:false} toggleDropdown=()=>{ this.setState({dropdownOpen:!this.state.dropdownOpen}); } resetTheme=evt=>{ evt.preventDefault(); this.setState({theme:null}); } chooseTheme=(theme,evt)=>{ evt.preventDefault(); this.setState({theme}); } render(){ const{theme,dropdownOpen}=this.state; constthemeClass=theme?theme.toLowerCase():'secondary'; return( {theme||'Default'} {theme||'Custom'}Theme this.chooseTheme('Primary',e)}>PrimaryTheme this.chooseTheme('Danger',e)}>DangerTheme this.chooseTheme('Success',e)}>SuccessTheme DefaultTheme ); } } exportdefaultThemeSwitcher; Herewehaverebuiltourinitialexampleusingreactstrap.Weimportacoupleofcomponentsfromreactstrap.SeethereactstrapButtonDropdowndocumentationtolearnmore. First,wesetupthecomponent’sstatewithtwoproperties: themepropertyinitializedtonull dropdownOpeninitializedtofalse.ThispropertywillbeusedintheButtonDropdowncomponentfromreactstraptomaintainthetogglestateofthedropdown. WealsodefineatoggleDropdown()methodtotoggletheopenstateofthedropdown.ThiswillalsobeusedintheButtonDropdowncomponent. reactstrapalsoprovidesanuncontrolledcomponentUncontrolledButtonDropdownthatdoesnotrequiretheisOpenproporthetogglehandlerproptowork.Inmostcases,thiscanbeusedinsteadofusingButtonDropdown. EachiteminthedropdownmenuisrenderedusingtheDropdownItemcomponent.NoticehowwespecifythebuttonsizeontheDropdownTogglecomponentusingthesizeprop.AlsonoticehowwearepassingthethemeClasstothecolorproponboththeButtonandDropdownTogglecomponentstodynamicallychangethebuttoncolorbasedonthestate’stheme. WealsosettheonClickhandleroneachDropdownItemjustlikewedidbefore,usingthechooseTheme()andresetTheme()handlerswedefinedearlier. Finally,wewillmodifythesrc/index.jsfiletolooklikethefollowingsnippet: import'bootstrap/dist/css/bootstrap.min.css'; importReactfrom'react'; importReactDOMfrom'react-dom'; import'./index.css'; importAppfrom'./App'; importThemeSwitcherfrom'./ThemeSwitcher'; importregisterServiceWorkerfrom'./registerServiceWorker'; ReactDOM.render(,document.getElementById('root')); registerServiceWorker(); Here,wefirstimporttheBootstrapminifiedCSSfile.WealsoimportourThemeSwitchercomponentandrenderittotheDOM. Ifyouruntheappnowwiththecommandyarnstartornpmstart.Yourappshouldstartonport3000andshouldlooklikethefollowingdemo: reactstrapDemo CreateaReactappwithBootstrap Let’spushthisabitfurthertocreateanappwithsomemoredetails.WewilltrytouseasmuchBootstrapclassesandcomponentsaspossible.WewillalsousereactstrapforintegratingBootstrapwithReact,sinceitsupportsBootstrap4. Wewillusethecreate-react-appcommand-linetooltocreateourapp.Ensurethatyouhavethecreate-react-apptoolinstalledonyourmachine.Hereisascreenshotofwhatwewillbecreating. AppScreenshot CreateanewReactappusingcreate-react-appasfollows: create-react-appsample-app Next,goaheadandinstallthedependenciesasfollows: yarnaddaxiosbootstrapreactstrap Noticeherethatweinstallaxiosasadependency.Axiosisapromise-basedHTTPclientforthebrowserandNode.js.ItwillenableustofetchpostsfromtheBaconIpsumJSONAPI. Makealittlemodificationtothesrc/index.jsfiletoincludetheBootstrapminifiedCSSfile.Itshouldlooklikethefollowingsnippet: import'bootstrap/dist/css/bootstrap.min.css'; importReactfrom'react'; importReactDOMfrom'react-dom'; import'./index.css'; importAppfrom'./App'; importregisterServiceWorkerfrom'./registerServiceWorker'; ReactDOM.render(,document.getElementById('root')); registerServiceWorker(); Createanewdirectorynamedcomponentsinthesrcdirectoryofyourproject.Createanewfile,Header.js,inthejust-createdcomponentsdirectorywiththefollowingcontent: importReactfrom'react'; importlogofrom'../logo.svg'; import{ Container,Row,Col,Form,Input,Button,Navbar,Nav, NavbarBrand,NavLink,NavItem,UncontrolledDropdown, DropdownToggle,DropdownMenu,DropdownItem }from'reactstrap'; constAVATAR='https://www.gravatar.com/avatar/429e504af19fc3e1cfa5c4326ef3394c?s=240&d=mm&r=pg'; constHeader=()=>(
Home Events Learn LearnReact Documentation Tutorials Courses Search
); exportdefaultHeader; ThecomponentwejustcreatedinthissnippetistheHeadercomponentthatcontainsthenavigationmenu.Next,wewillcreateanewfilenamedSideCard.jsinthecomponentsdirectorywiththefollowingcontent: importReact,{Fragment}from'react'; import{ Button,UncontrolledAlert,Card,CardImg,CardBody, CardTitle,CardSubtitle,CardText }from'reactstrap'; constBANNER='https://i.imgur.com/CaKdFMq.jpg'; constSideCard=()=>( Accountnotactivated. GladChinda WebDeveloper,Lagos Full-stackwebdeveloperlearningnewhacksonedayatatime.Webtechnologyenthusiast.Hackingstuffs@theflutterwave. ViewProfile ); exportdefaultSideCard; Next,createanewfilenamedPost.jsinthecomponentsdirectoryandaddthefollowingcodesnippettoit: importReact,{Component,Fragment}from'react'; importaxiosfrom'axios'; import{Badge}from'reactstrap'; classPostextendsComponent{ state={post:null} componentDidMount(){ axios.get('https://baconipsum.com/api/?type=meat-and-filler&paras=4&format=text') .then(response=>this.setState({post:response.data})); } render(){ return( {this.state.post&& Editor'sPick New GettingStartedwithReact {this.state.post} } ); } } exportdefaultPost; HerewecreatedaPostcomponentthatrendersapostonthepage.Weinitializethestateofthecomponentwithapostpropertysettonull.Whenthecomponentmounts,weuseaxiostofetcharandompostoffourparagraphsfromtheBaconIpsumJSONAPIandupdatethepostpropertyinthestate. Finally,modifythesrc/App.jsfiletolooklikethefollowingsnippet: importReact,{Fragment}from'react'; importaxiosfrom'axios'; import{Container,Row,Col}from'reactstrap'; importPostfrom'./components/Post'; importHeaderfrom'./components/Header'; importSideCardfrom'./components/SideCard'; constApp=()=>(
); exportdefaultApp; HerewesimplyincludetheHeader,SideCard,andPostcomponentsintheAppcomponent.NoticehowweuseacoupleofresponsiveutilityclassesprovidedbyBootstraptoadaptourapptodifferentscreensizes. Ifyouruntheappnowwiththecommandyarnstartornpmstart,yourappshouldstartonport3000andshouldlookexactlylikethescreenshotwesawearlier. Conclusion Inthistutorial,weexploredafewdifferentwaysinwhichwecanintegrateBootstrapwithourReactapps.WehavealsoseenhowwecanusetwoofthemostpopularReactBootstraplibraries,namelyreact-bootstrapandreactstrap. WehaveonlyusedafewBootstrapcomponentsinthistutorial,suchasalert,badge,dropdown,navbar,nav,form,button,card,etc.ThereisstillacoupleofBootstrapcomponentsyoucanexperimentwith,suchastables,modals,tooltips,carousel,jumbotron,pagination,tabs,etc. Youcancheckthedocumentationofthepackagesweusedinthistutorialtofindoutmorewaystheycanbeused.ThesourcecodeforallthedemoappsinthistutorialcanbefoundonGitHub. FullvisibilityintoproductionReactappsDebuggingReactapplicationscanbedifficult,especiallywhenusersexperienceissuesthatarehardtoreproduce.Ifyou’reinterestedinmonitoringandtrackingReduxstate,automaticallysurfacingJavaScripterrors,andtrackingslownetworkrequestsandcomponentloadtime,tryLogRocket.LogRocketislikeaDVRforwebandmobileapps,recordingliterallyeverythingthathappensonyourReactapp.Insteadofguessingwhyproblemshappen,youcanaggregateandreportonwhatstateyourapplicationwasinwhenanissueoccurred.LogRocketalsomonitorsyourapp'sperformance,reportingwithmetricslikeclientCPUload,clientmemoryusage,andmore.TheLogRocketReduxmiddlewarepackageaddsanextralayerofvisibilityintoyourusersessions.LogRocketlogsallactionsandstatefromyourReduxstores.ModernizehowyoudebugyourReactapps—startmonitoringforfree. Sharethis:TwitterRedditLinkedInFacebook GladChindaFollow Full-stackwebdeveloperlearningnewhacksonedayatatime.Webtechnologyenthusiast.Hackingstuffs@theflutterwave. Uncategorized #react «HowtosetupinternationalizationinReactusingLingui.js WhichChromeDevToolsimproveaccessibility?» BuildatreasurywalletwithmultisignatureGnosisSafe ArjunaSkyKok Mar15,2022 11minread RunbackendtasksinFlutterusingCloudFunctions SouvikBiswas Mar15,2022 8minread BuildaTic-Tac-ToegamewithReactHooks ChidumeNnamdi Mar15,2022 8minread 4Repliesto“UsingBootstrapwithReact” Awesome! Greatarticleuponreact+bootstrapcombination! Great!Thanksforthispost. Nicepost!Justacomment:MenuItemhasbeenchangedtoDropdownItem Nicepost! LeaveaReplyCancelreply


請為這篇文章評分?