React bootstrap not styling my react components - Stack ...

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

Now the responsive positioning is working (where as before I saw react-bootstrap rendering the correct class names, but without styling). Home Public Questions Tags Users Collectives ExploreCollectives FindaJob Jobs Companies Teams StackOverflowforTeams –Collaborateandshareknowledgewithaprivategroup. CreateafreeTeam WhatisTeams? Teams CreatefreeTeam CollectivesonStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore Reactbootstrapnotstylingmyreactcomponents AskQuestion Asked 4years,3monthsago Modified 6monthsago Viewed 68ktimes 30 6 JuststartedoutusingReactyesterdaysosettingupademoapp.Environmentis: Typescript Webpack React&ReactDOM I'mtryingtosetupBootstrapstyles. IfollowedthistutorialalongbutmodifiedittosuitTypescript: https://medium.com/@victorleungtw/how-to-use-webpack-with-react-and-bootstrap-b94d33765970 Everythingworks,thepagedisplaysthesigninformandtheBootstrapHTMlisoutputbyReact-Bootstrap.Butthestylesarenotappliedtotheelements,it'sjustaplainHTMLpagewithnoneoftheBootstrapstylesapplied.I'mnotsurewhatI'mmissingfromtheconfig: webpack.config.js I'veaddedtheloadersthroughnpmasmentionedinthetutorial,butalsoadjustedtosetupTypescriptmodulesfromthecss. module.exports={ entry:{ catalog:"./src/apps/CatalogApp.tsx", auth:"./src/apps/AuthApp.tsx" }, output:{ filename:"[name].bundle.js", publicPath:"/build/", path:__dirname+"/dist" }, //Enablesourcemapsfordebuggingwebpack'soutput. devtool:"source-map", resolve:{ //Add'.ts'and'.tsx'asresolvableextensions. extensions:[".ts",".tsx",".js",".json"] }, module:{ rules:[ //Allfileswitha'.ts'or'.tsx'extensionwillbehandledby'awesome-typescript-loader'. { test:/\.tsx?$/, loader:"awesome-typescript-loader" }, //Alloutput'.js'fileswillhaveanysourcemapsre-processedby'source-map-loader'. { enforce:"pre", test:/\.js$/, loader:"source-map-loader" }, //cssloader { test:/\.css$/, loader:"typings-for-css-modules-loader?modules" }, { test:/\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/, loader:'url-loader?limit=10000&mimetype=application/font-woff' }, { test:/\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader:'url-loader?limit=10000&mimetype=application/octet-stream' }, { test:/\.eot(\?v=\d+\.\d+\.\d+)?$/, loader:'file-loader' }, { test:/\.svg(\?v=\d+\.\d+\.\d+)?$/, loader:'url-loader?limit=10000&mimetype=image/svg+xml' } ] }, //Whenimportingamodulewhosepathmatchesoneofthefollowing,just //assumeacorrespondingglobalvariableexistsandusethatinstead. //Thisisimportantbecauseitallowsustoavoidbundlingallofour //dependencies,whichallowsbrowserstocachethoselibrariesbetweenbuilds. externals:{ "react":"React", "react-dom":"ReactDOM" } }; AuthApp.tsx Thisismyentrypointfortheapplication. import*asReactfrom"react"; import*asReactDOMfrom"react-dom"; import{SigninForm}from"../components/users/SigninForm"; import{MiniCart}from'../components/cart/MiniCart'; import{UserMenu}from'../components/users/UserMenu'; import*asbsfrom'bootstrap/dist/css/bootstrap.css'; import*asbstfrom'bootstrap/dist/css/bootstrap-theme.css'; if(document.getElementById("signin-form")){ ReactDOM.render( , document.getElementById("signin-form") ); } if(document.getElementById('cart')){ ReactDOM.render( , document.getElementById('cart') ); } if(document.getElementById('user-menu')){ ReactDOM.render( , document.getElementById('user-menu') ); } SigninForm.tsx AndtherelevantUIforthesigninform. import*asReactfrom'react'; import*asReactDOMfrom"react-dom"; import{Button,Col,Row}from'react-bootstrap'; import{Spinner}from'../shared/Spinner'; interfaceSigninFormProps{ } interfaceSigninFormState{ email:string; password:string; } exportclassSigninFormextendsReact.Component{ constructor(props:SigninFormProps){ super(props); this.state={ email:'', password:'' }; this.handleChange=this.handleChange.bind(this); this.handleSubmit=this.handleSubmit.bind(this); } handleChange(event:any){ this.setState({[event.target.name]:event.target.value}); } handleSubmit(event:any){ event.preventDefault(); console.log('Submittingform',this.state); } render(){ return( Email Password RightSide ); } } reactjswebpack-2 Share Follow askedNov17,2017at15:51 RichardGRichardG 4,4371010goldbadges4343silverbadges8383bronzebadges Addacomment  |  7Answers 7 Active Oldest Votes 53 Iranintothesameissueandthisworkedforme--> Iendedupinstallingbootstrapwithnpm: 1)npmi--savebootstrap Then,inindex.js(whereIrenderApp.js)Iimportedbootstrap'sminifiedcssfilefromnodes_moduleslikeso: 2)import'../node_modules/bootstrap/dist/css/bootstrap.min.css'; Nowtheresponsivepositioningisworking(whereasbeforeIsawreact-bootstraprenderingthecorrectclassnames,butwithoutstyling). Note:https://react-bootstrap.github.io/getting-started/introductionsaysyoushouldaddthecsstotheheadofindex.html.Ididnothavesuccessdoingitthisway. Share Follow answeredAug24,2018at21:48 JamieRoninJamieRonin 53144silverbadges44bronzebadges 3 1 Ialsohavenothadsuccesswithaddingthescripttagstotheindex.html...butitsprobablybecausetherearesomethingsI'mnotunderstanding.Thisworkedforme! – MikeKellogg Apr24,2019at15:32 formeitwasjust'bootstrap/dist/css/bootstrap.min.css'youdontneedtoexplicitlyimportfrom'node_modules'irrespectiveofthepartunderneath'src'youmaybe. – khanna Apr18,2020at12:36 yousavedtheyearbro!! – Charleskimani Jan27,2021at9:49 Addacomment  |  27 Firstofwhatyouneedtoisto InstallBootstrapusingNPM npminstall--savebootstrap then gofor writingthisstatementinwhichcomponentyouhavetousebootstrap,Thisworksinmycase. import'bootstrap/dist/css/bootstrap.css'; CSSStylingwillstartworking.:) HappyCoding! Share Follow answeredJun11,2019at8:26 SyedUmerHasanSyedUmerHasan 41566silverbadges99bronzebadges 2 1 Thisideasolvedmyissue.getbootstrap.com/docs/4.4/getting-started/webpack/… – AswinPrasad Apr11,2020at22:25 3 import'bootstrap/dist/css/bootstrap.css';Worksforme.. – AmitDwivedi Mar10,2021at18:26 Addacomment  |  8 Thewebpackconfigyouuseisalittledifferentfromthemediumarticle. Inthemediumarticle,theauthorusesstyle-loaderandcss-loadertoprocesscssfile. module.exports={ entry:'./main.js', output:{path:__dirname,filename:'bundle.js'}, module:{ loaders:[ ... { test:/\.css$/, loader:"style-loader!css-loader" }, ... ] }, }; style-loaderwillinjectthecsscodetotag.Sothatiswhythetutorialwork Inyourwebpackconfig,youusetypings-for-css-modules-loadertoloadcss.Withthisloader,youneedtopassthecssclassvariablenametoclassName. Itmeansyoushouldwritethecodelike(simplifysomecode): import*asReactfrom"react"; import*asbsfrom'bootstrap/dist/css/bootstrap.css'; import*asbstfrom'bootstrap/dist/css/bootstrap-theme.css'; import{Button,Col,Row}from'react-bootstrap'; import{Spinner}from'../shared/Spinner'; exportclassSigninFormextendsReact.Component{ ... render(){ return( Email RightSide ); } } Passbt[classname]toclassName. Ithinkitwillwork. btw,Ifindanothermediumarticleusingtypings-for-css-modules-loader->link. Share Follow answeredNov17,2017at16:42 Chen-TaiChen-Tai 3,24533goldbadges1919silverbadges3434bronzebadges 6 thxwilltrythiswhenIgethometoday.butitwouldntfixthelayoutcomponentsright?therowandcoltagsarenotworkingeither. – RichardG Nov18,2017at3:22 alsothearticleistheoneIreferencedtochoosetypingscssloader.itseemstoconcludethatjustimportingthestylessheetshouldworkunlessIreaditwrong... – RichardG Nov18,2017at3:24 1 @RichardGThereact-bootstrapdocsaid:BecauseReact-Bootstrapdoesn'tdependonaverypreciseversionofBootstrap,wedon'tshipwithanyincludedcss.Soyouneedtoincludebootstrapcssbyyourself. – Chen-Tai Nov18,2017at3:26 actuallythey'realsousingstyleloaderandnamedexportsoption.maybeusingstyleloaderwillfixit. – RichardG Nov18,2017at3:30 Yeah,that'sright.Themediumarticleyoupostisimportbootstrapinjsfileandusecss-loader|style-loadertoloadit.Thatisonemethodtodothetrick. – Chen-Tai Nov18,2017at3:32  |  Show1morecomment 8 Notsureifitisrelevantatthistimeicheckedyourpost. Howeveriamabletousereact-bootstrap, Accordingtoreact-bootstrap,youwillhavetoadd" whichiaddedinintomyindex.htmlheadertag. Andihavealsoaddedimport"react-bootstrap/dist/react-bootstrap.min.js";inmyapp.js. Share Follow answeredFeb28,2019at5:52 csamleongcsamleong 53911goldbadge88silverbadges2222bronzebadges Addacomment  |  7 AtApp.cssjustpastethefollowingimport: @import"bootstrap/dist/css/bootstrap.css"; Share Follow editedJan17,2021at19:34 DuDa 3,51144goldbadges1414silverbadges3636bronzebadges answeredJan17,2021at18:27 DarKayserLeoDarKayserLeo 7111silverbadge11bronzebadge Addacomment  |  2 Pleasetrytoaddthislineinindex.js import'bootstrap/dist/css/bootstrap.min.css'; AddingthistoApp.jsfiledoesn'tworkforme Share Follow editedApr7,2021at6:37 answeredApr6,2021at18:14 AnoopAnoop 2133bronzebadges Addacomment  |  1 Alongwithbootstrap.min.js,weneedtousebootstrap.min.cssinordertohavebootstrapworking.Visithttps://www.bootstrapcdn.com/andcopylinksunderCSSandJavaScriptandpasteitintheHTMLfileunderheadtag. Useasbelowandchangethebootstrapversionaccordingly. Share Follow editedSep17,2021at6:35 answeredSep17,2021at6:13 VidyaSagarHJVidyaSagarHJ 7133bronzebadges Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedreactjswebpack-2oraskyourownquestion. TheOverflowBlog Howshardingadatabasecanmakeitfaster FeaturedonMeta StackExchangeQ&AaccesswillnotberestrictedinRussia PlannedmaintenancescheduledforFriday,March18th,00:30-2:00UTC... AnnouncinganA/BtestforaTrendingsortoption Improvingthefirst-timeaskerexperience-Whatwasaskingyourfirst... Linked 19 Bootstrapclass"text-center"notworking 0 Howtogivepaddingtocolinreactbootstrap? Related 1694 LoopinsideReactJSX 927 CanyouforceaReactcomponenttorerenderwithoutcallingsetState? 1295 WhatdothesethreedotsinReactdo? 1980 ProgrammaticallynavigateusingReactrouter 843 HowdoIconditionallyaddattributestoReactcomponents? 928 WhatisthedifferencebetweenReactNativeandReact? 3 Webpackthrowingerror"Youmayneedanappropriateloader"inreactwithtypescript 0 CSSisnotoverridingReact-BootstrapandBootstrapasexpected HotNetworkQuestions Canawebsiteinitselfbedangerous? Whattodoifareviewer'squestionisnonsense HowcanImeasuretheanglebetweentwostars? Isthereanyvariationknowntothesumoftwosquarestheorem? Placebodopinginsport Novelidentification:windmakesEarth'ssurfaceuninhabitable CanIdrivealow-voltageMOSFETgatedirectlyfromamicrocontroller? Makingatablecolumnnarrower(tabu) Wouldthelossofintoxicationcauseamasswithdrawalevent? WherecanIdownloadtheSoyuzCrewOperationsManual? WhattodoifyouareassignedtoTAacourseyouarenotqualifiedtoteach? LTSpice:Whyaremycapacitorshalfchargedatsimulationstart? QualityofShowwithtwoGraphics3D:intersectionquality DoheavyhumanlossesputpressureonanautocraticleaderlikePutin? CanTuckerCarlsonbesanctionedbytheUSgovernment? Isitabadsign?Searchcommitteedidnoteverreachouttoreferences,evenbeforeandaftercampusvisit Opening/Closingprayerintheagendaatanacademicconference-why? HowdoesclassbalancechangewhenIremovespellcasting? WhoisDumbledorecallingthe"wrongman"whenheaccusesFudge? WhathappenswhentheAidspellendsonacreaturewhileitshitpointmaximumhasbeenchangedtoanothervalue? ArethereanyspeciesinStarTrekwhosedietaryrequirementsaredifferentenough,thattheycouldn'tsurviveone.g.HumanorVulcanfood? Howtoplacecertainpiecesona5x5chessboardwithoutanyofthemattackingeachother? WhyisLadyJaneGreycalledLadyinsteadofQueen? ComponentToleranceProbability morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-js Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?