React-starter-kit: Bootstrap implementation

Created on 20 Jul 2015  路  55Comments  路  Source: kriasoft/react-starter-kit

You are writing about Bootstrap but I don't see implementation of this frontend framework inside your starter-kit app htmls/css/less files. This is not just installing bootstrap but also changes in current layout.

  1. Are you going to use it in new version?
  2. Am I right - to use bootstrap,jquery or other frontend/view libraries with React we should use Bower?

Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

Most helpful comment

For everyone that still have this problem, I have found a solution to load Bootstrap 3 css and font files into App component without renamed classNames.

  • Install Bootstrap from NPM npm install --save bootstrap@3
  • Add a new loader into tools/webpack.config.js before css loader
      {
        test: /\.css/,
        include: /node_modules/,
        loaders: [
          'isomorphic-style-loader',
          `css-loader?${JSON.stringify({
            sourceMap: DEBUG,
            // CSS Modules https://github.com/css-modules/css-modules
            modules: false,
            localIdentName: '[local]',
            // CSS Nano http://cssnano.co/options/
            minimize: !DEBUG,
          })}`,
          'postcss-loader?pack=default',
        ],
      },
  • In the default css loader add exclude: /node_modules/, right after test: /\.css/,
      {
        test: /\.css/,
        exclude: /node_modules/,
        loaders: [
          'isomorphic-style-loader',
          `css-loader?${JSON.stringify({
            sourceMap: DEBUG,
            // CSS Modules https://github.com/css-modules/css-modules
            modules: true,
            localIdentName: DEBUG ? '[name]_[local]_[hash:base64:3]' : '[hash:base64:4]',
            // CSS Nano http://cssnano.co/options/
            minimize: !DEBUG,
          })}`,
          'postcss-loader?pack=default',
        ],
      },
  • In src/components/App/App.js add a new import
import bt from 'bootstrap/dist/css/bootstrap.css?root=./node_modules/bootstrap/dist/'; // eslint-disable-line import/no-unresolved, max-len
  • In componentWillMount function add this.removeBootstrap = insertCss(bt); at the end
  componentWillMount() {
    const { insertCss } = this.props.context;
    this.removeCss = insertCss(s);
    this.removeBootstrap = insertCss(bt);
  }
  • In componentWillUnmount function add this.removeBootstrap(); at the end
  componentWillUnmount() {
    this.removeCss();
    this.removeBootstrap();
  }

With this now you should be able to load correctly Bootstrap 3 without classNames renamed.

All 55 comments

  1. If you want to use Twitter Bootstrap, you may want to look at React Bootstrap library which you can install via npm install react-bootstrap
  2. In general it's better to use npm as opposed to Bower whenever possible. E.g. npm install jquery, import $ from 'jquery';

I put React Bootstrap in my app,now i have to include the bootstrap css file, but how ?

I include in templates/index.html ??

You can reference it in src/components/App/App.css like so:

@import '../../../node_modules/bootstrap/less/bootstrap.css';

@import '../../../node_modules/bootstrap/less/bootstrap.css'

or

@import '../../../node_modules/bootstrap/less/bootstrap.less ?

@weslley39 take a look into node_modules/bootstrap folder for the correct file name/path, it might be:

@import '../../../node_modules/bootstrap/dist/bootstrap.css';

@koistya

i put @import '../../../node_modules/bootstrap/dist/css/bootstrap.css';

but now, i have an error:

Error: Cannot find module "../../../node_modules/bootstrap/dist/fonts/glyphicons-halflings-regular.eot"
    at webpackMissingModule (/Users/weslleyneri/apps/reactjs/react-start-kit/build/webpack:/src/components/App/App.css:6:12817)
    at Object.<anonymous> (/Users/weslleyneri/apps/reactjs/react-start-kit/build/webpack:/src/components/App/App.css:6:12817)
    at __webpack_require__ (/Users/weslleyneri/apps/reactjs/react-start-kit/build/webpack:/webpack/bootstrap 95b678e15f4e72628b80:19:1)
    at Object.<anonymous> (/Users/weslleyneri/apps/reactjs/react-start-kit/build/webpack:/src/components/App/App.js:3:41)
    at Object.<anonymous> (/Users/weslleyneri/apps/reactjs/react-start-kit/build/webpack:/src/components/App/App.js:33:19)
    at __webpack_require__ (/Users/weslleyneri/apps/reactjs/react-start-kit/build/webpack:/webpack/bootstrap 95b678e15f4e72628b80:19:1)
    at Object.<anonymous> (/Users/weslleyneri/apps/reactjs/react-start-kit/build/webpack:/src/Router.js:5:37)
    at Object.<anonymous> (/Users/weslleyneri/apps/reactjs/react-start-kit/build/webpack:/src/Router.js:39:22)
    at __webpack_require__ (/Users/weslleyneri/apps/reactjs/react-start-kit/build/webpack:/webpack/bootstrap 95b678e15f4e72628b80:19:1)
    at Object.<anonymous> (/Users/weslleyneri/apps/reactjs/react-start-kit/build/webpack:/src/server.js:8:40)

But this file is there.

I had that issue and for this you need to add in the loaders of webpack the extension of eot like

{
      test: /\.eot/,
      loader: 'url-loader?mimetype=application/vnd.ms-fontobject'
    }

@rodolfo2488 sorry, but where is this file ?

Thanks, now it works.

For work i had to put some more loaders, like:

{
      test: /\.eot/,
      loader: 'url-loader?mimetype=application/vnd.ms-fontobject'
    }, {
      test: /\.ttf/,
      loader: 'url-loader?mimetype=application/x-font-ttf'
    }, {
      test: /\.woff/,
      loader: 'url-loader?mimetype=application/font-woff'
    }, {
      test: /\.woff2/,
      loader: 'url-loader?mimetype=application/font-woff2'
    }

Yes, eot is just for IE. prob Bootstrap load all of them :). Good job!

If you can send a PR with these loaders, that would be nice!

@koistya I try a PR in https://github.com/kriasoft/react-starter-kit/pull/239 if I could get the feedback from @weslley39 would be great!

Worked really well for me

Including @import '../../../node_modules/bootstrap/dist/css/bootstrap.css'; in App.css cause

ERROR in ./src/components/App/App.css
Module not found: Error: Cannot resolve 'file' or 'directory' ../fonts/glyphicons-halflings-regular.eot in C:\Users\fodef\Source\react-start-kit\src\components\App
 @ ./src/components/App/App.css 6:12311-12363 6:12386-12438
Error: Cannot find module "../fonts/glyphicons-halflings-regular.eot"

It trying to find glyphicons-halflings-regular.eot relative to App.css not bootstrap.css
I use Windows

Mm.. maybe you should try adding:

import '../../../node_modules/bootstrap/dist/css/bootstrap.css?root=./node_modules/bootstrap/dist/';

To your top-level React component (App.js)

I'm trying to add in App.cs this row @import '../../../node_modules/bootstrap/dist/css/bootstrap.css?root=./node_modules/bootstrap/dist/';

ERROR in ./src/components/App/App.css
Module build failed: Error: C:\Users\fodef\Source\react-start-kit\src\components\App\App.css:2:1: Failed to find '../../../node_modules/bootstrap/dist/css/bootstrap.css?root=./node_modules/bootstrap/dist/' from C:\Users\fodef\Source\react-start-kit

And trying to add in App.js import '../../../node_modules/bootstrap/dist/css/bootstrap.css?root=./node_modules/bootstrap/dist/';

ERROR in ./~/bootstrap/dist/css/bootstrap.css?root=./~/bootstrap/dist/
Module parse failed: C:\Users\fodef\Source\react-start-kit\node_modules\bootstrap\dist\css\bootstrap.css?root=./node_modules/bootstrap/dist/ Line 7: Unexpected token {
You may need an appropriate loader to handle this file type.

You can try to configure a separate loader for bootstrap.css file in webpack config tools/config.js, something like this:

{
  test: /bootstrap\.css/,
  loader: 'css-loader?root=./node_modules/bootstrap/dist/'
}

It did not help :(

ERROR in ./src/components/App/App.css
Module not found: Error: Cannot resolve 'file' or 'directory' ../fonts/glyphicons-halflings-regular.eot in C:\Users\fodef\Source\react-start-kit\src\components\App
 @ ./src/components/App/App.css 6:12416-12468 6:12491-12543

I tried it and this and that in App.css
@import '../../../node_modules/bootstrap/dist/css/bootstrap.css';
@import 'bootstrap.css';
with tools\config.js

      {
        test: /bootstrap\.css/,
        loader: 'css-loader?root=./node_modules/bootstrap/dist/',
      },

@f0def have you placed this /bootstrap\.css/ loader before /\.css$ one?

I add it here:

  module: {
    loaders: [
      {
        test: /bootstrap\.css/,
        loader: 'css-loader?root=./node_modules/bootstrap/dist/',
      },
      {
        test: /\.json$/,
        loader: 'json-loader',
      }, {
        test: /\.txt$/,
        loader: 'raw-loader',
      }, {
        test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
        loader: 'url-loader?limit=10000',
      }, {
        test: /\.(eot|ttf|wav|mp3)$/,
        loader: 'file-loader',
      },
    ],
  },

@f0def do you resolve it ?

No, i don't

Personnaly I just rebase the url with the 'postcss-url' plugin

Install the postcss-url with npm install --save-dev postcss-url

Then update your tools\config.js like this

postcss: function plugins() {
    return [
      require('postcss-import')({
        onImport: files => files.forEach(this.addDependency),
      }),
      require('postcss-url')({
        copy: 'rebase',
      }),
      require('postcss-nested')(),
      require('postcss-cssnext')({ autoprefixer: AUTOPREFIXER_BROWSERS }),
    ];
  },

@ThatCheck It work for me. thanks.馃槃

How would I include the bootstrap JS file in the minification process?
I know I can just include it in the Html component manually but thats not ideal as its not part of the regular packaged JS

What was the solution to get react-bootstrap to work?

@ThatCheck, tools/config.js is missing - is it used by npm? And could you post the entire file?

Found a fork with the config code: https://github.com/kn4rfy/quantum/commit/919cf461b5e1ed67f4c5297919a25da618fbb8c6
Also adds react-bootstrap, which is more interesting than bootstrap it self.

@Elghtyplus thx.

I am having the same issue that @f0def seems to be having. I was able to get around it by (for now) gotten around it by putting my fonts from the bootstrap lib into the component directory.

What is happening is bootstrap is trying to include the fonts relative to the App.css file.

Found a fix as @Eightyplus posted:
Worked great!
Look forward to Bootstrap 4 and bootstrap-react integration.

@neosmedia, I am not sure what you are asking.

Bootstrap is loading, however, when bootstrap attempts to load the fonts, it is attempting to do so relative to the App.css file and not bootstrap's css file.

@Eightyplus Thx. It works for me.

@koistya @Eightyplus styles is working now but JS functionality is missing component is broken,
so we also have to include bootstrap.min.js file
if yes then please guide how to include it

@neosmedia - react-starter-kit does not use bootstrap, but you can integrate it with
npm install react-bootstrap --save

Then you can use the bootstrap components after import, e.g.
import {Navbar, Nav, NavItem, NavDropdown, MenuItem, ProgressBar} from "react-bootstrap";

@anilGupta - sorry I don't know, since I only use the styling. But my guess is that you have to add a bootstrap loader in webpack.config.js

@Eightyplus can you please provide me sample config

@Eightyplus i am not able to find the reference to bootstrap.min.js in ur config file

Anyone have any more luck getting Bootstrap installed? I'm ready to throw my laptop out of the window over this one.

Here's what I've tried (on a fresh download of the starter kit):

  1. Added bootstrap from NPM with npm install bootstrap --save-dev.
  2. Added this line to App/App.scss:

@import '../../../node_modules/bootstrap/dist/css/bootstrap.css';

(And also removed the reference to normalize.css; as Bootstrap already includes normalize.css ;) )

  1. Tried every single solution that's already been posted in this thread, and every combination thereof, and none of them prevented me from getting the error where Bootstrap can't find the font files because it's looking in src/components/App/ rather than in /node_modules/bootstrap/dist.
  2. Eventually I realised that I don't even need the font files anyway, because I have no intention of using Glyphicons, so I opted for the extremely hacky solution of opening up /node_modules/bootstrap/dist/css/bootstrap.css and manually removing all references to the Glyphicon fonts.
  3. I then got an error because bootstrap also tries to load the source map file (bootstrap.css.map), but of course it's still looking in the wrong place. So I also removed the following line from bootstrap.css (it's right at the bottom):

/*# sourceMappingURL=bootstrap.css.map */

  1. And now my page loads... but half the Bootstrap styles aren't applied. When I look in the inspector, it seems that all the classes in the Bootstrap file are having the prefix "App_" added to them along with a random suffix. E.g. where my raw css file says .navbar { display: none; }, what's output to the browser says .App_navbar_2h4 { display: none; } - and since there are no elements on my page which have this class (nor can I add them, because the 2h4 suffix is different for every morphed class and seems to be random, so I can't predict what the classes will even be), the styles never get applied.

What am I doing wrong? Can't believe how difficult it is to do something as simple as adding a CSS file!

I now have react-bootstrap successfully installed, building, and rendering without warnings or errors within react starter kit. I also have the bootstrap.css file imported in the app.scss file.

@import '../../../node_modules/bootstrap/dist/css/bootstrap.css';

However, my react-bootstrap components are not being styled when rendered. Please notice the unstyled navigation bar in my react starter kit sample.

Next I tried adding an explicit link to bootstrap from inside Html.js:

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />      

Suddenly the bootstrap styling works! But I feel this isn't the right way to solve the problem. Why does the app.scss import approach, recommended by @koistya, not work?

@Mystagogue did you find fix for this problem i am also running into same issue , no styles applying
@georgemillo "I'm ready to throw my laptop out of the window over this one" your comment make me lol for few min seriously

If you're using the latest (unreleased) react-starter-kit you're probably seeing the effects of the new CSS loader (pre-css?) when you use the import statement. Bootstrap components reference global css classes, but precss/postss or whatever namespaces all the classes to avoid collisions. I'm not 100% sure this is the issue you're seeing, but it could be.
Personally I'm finding the new css style a bit clumsy, so you may wish to rip it out and go with old-style global classes. Or I think you can turn off the namespacing maybe. You can make classes global by using :global(.myclass) as your selector in the scss file instead of just .myclass.

@nss213 You're right, the CSS loaders are screwing with the global css classes. Can confirm this, just got it working myself and the fix was to have webpack preserve the global styles for .css files.
@georgemillo @Mystagogue in case you're still working on this, here's the relevant portion of the config file & App.js which will have webpack preserve the bootstrap global css classes

webpack.config.js

...
    loaders: [
      {
        test: /\.jsx?$/,
        include: [
          path.resolve(__dirname, '../node_modules/react-routing/src'),
          path.resolve(__dirname, '../src'),
        ],
        loader: 'babel-loader',
      }, {
        test: /\.css$/,
        loaders: [
          'isomorphic-style-loader',
          `css-loader?sourceMap&modules&localIdentName=[local]`,
          'postcss-loader?parser=postcss-scss',
        ],
      }, {
        test: /\.scss$/,
        loaders: [
          'isomorphic-style-loader',
          `css-loader?${DEBUG ? 'sourceMap&' : 'minimize&'}modules&localIdentName=` +
          `${DEBUG ? '[name]_[local]_[hash:base64:3]' : '[hash:base64:4]'}`,
          'postcss-loader?parser=postcss-scss',
        ],
      }, {
        test: /\.json$/,
        loader: 'json-loader',
      }, {
        test: /\.txt$/,
        loader: 'raw-loader',
      }, {
        test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
        loader: 'url-loader?limit=10000',
      }, {
        test: /\.(eot|ttf|wav|mp3)$/,
        loader: 'file-loader',
      },
    ],
  ...

App.js

...

import bs from  '../../../node_modules/bootstrap/dist/css/bootstrap.css';

...

  componentWillMount() {
    this.context.insertCss(bs);
    ...
  }

With this change, react-bootstrap will work just fine.
Not sure how easy it will be to extend the global bootstrap styles, though.

To those above having issues with the loaders prefixing global styles when imported, I found that something like:

:global {
  @import '<path to CSS>'
}

at the top of App.scss worked for me without having to change the loaders at all. But for some reason the fonts are still not being loaded correctly, still looking into this.

This is what I did to load react-bootstrap:

install https://github.com/shakacode/bootstrap-loader
install https://github.com/react-bootstrap/react-bootstrap

add this to your webpack loaders:
}, { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url-loader?limit=10000&mimetype=application/font-woff', }, { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'file-loader', }, {
modify clientConfig.entry
entry: ['./src/client.js', 'bootstrap-loader']
Add a file names .boostraprc to root directory
see examples of bootstrap config file: https://github.com/shakacode/bootstrap-loader/blob/master/.bootstraprc-3-default
(set all the Bootstrap scripts to false on the bottom)

this should work.

@heks yes, this works for client side. But about about server side? Don't you see flash when you hit refresh?

On the server side I am getting:

Error: Cannot find module './lib/bootstrap.loader!./no-op.js'
    at Function.Module._resolveFilename (module.js:326:15)
    at Function.Module._load (module.js:277:25)
    at Module.require (module.js:354:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (d:\projects\react-dashboard\node_modules\bootstrap-loader\loader.js:1:1)
    at Module._compile (module.js:398:26)
    at Object.Module._extensions..js (module.js:405:10)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Module.require (module.js:354:17)

https://github.com/shakacode/bootstrap-loader/issues/41

Guys, in case anyone is interested in a complete BS3 integration (client- and serverside with glyphicons) with RSK including an ability to use and override sass variables here is the fork https://github.com/flatlogic/react-starter-kit/tree/feature/bootstrap3

I can submit a PR from this fork, but I am not sure if @koistya wants bootstrap here :(
Anyway, we are going to keep fork in sync with RSK

Today I spent several hours trying to solve the BS integration (only the css part) problem.
Importing bootstrap.min.css from app.scss won't work because the url(../font/something) always use path relative to the bootstrap.min.css file.
It turned out that old style-loader works for me.
In my client.js, I have:

require('!style!css!../node_modules/bootstrap/dist/css/bootstrap.min.css');

That's it. I know it is kind of sloppy but I really don't want to spend any more time on it.
_(:蟹銈濃垹)_

Hello Does anyone use react-bootstrap and boostrap ?

I have problem with className renamed
for exemple `bn-successprefixed byApp_btn-sucessA``

Same problem as @georgemillo

@mika75 you may want to copy and paste isomorphic-style-loader entry here, just set modules: false on it, and tweak its search pattern so it would match only /bootstrap\.css$/ file.

I'm trying to get bootstrap to work, but and having issues with it even after attempting the above.

@Light1c3 See #646 or only commit https://github.com/kriasoft/react-starter-kit/commit/0eba0fde19189415d58d9ce90854e3c02d7eaeec for minimal working setup

For everyone that still have this problem, I have found a solution to load Bootstrap 3 css and font files into App component without renamed classNames.

  • Install Bootstrap from NPM npm install --save bootstrap@3
  • Add a new loader into tools/webpack.config.js before css loader
      {
        test: /\.css/,
        include: /node_modules/,
        loaders: [
          'isomorphic-style-loader',
          `css-loader?${JSON.stringify({
            sourceMap: DEBUG,
            // CSS Modules https://github.com/css-modules/css-modules
            modules: false,
            localIdentName: '[local]',
            // CSS Nano http://cssnano.co/options/
            minimize: !DEBUG,
          })}`,
          'postcss-loader?pack=default',
        ],
      },
  • In the default css loader add exclude: /node_modules/, right after test: /\.css/,
      {
        test: /\.css/,
        exclude: /node_modules/,
        loaders: [
          'isomorphic-style-loader',
          `css-loader?${JSON.stringify({
            sourceMap: DEBUG,
            // CSS Modules https://github.com/css-modules/css-modules
            modules: true,
            localIdentName: DEBUG ? '[name]_[local]_[hash:base64:3]' : '[hash:base64:4]',
            // CSS Nano http://cssnano.co/options/
            minimize: !DEBUG,
          })}`,
          'postcss-loader?pack=default',
        ],
      },
  • In src/components/App/App.js add a new import
import bt from 'bootstrap/dist/css/bootstrap.css?root=./node_modules/bootstrap/dist/'; // eslint-disable-line import/no-unresolved, max-len
  • In componentWillMount function add this.removeBootstrap = insertCss(bt); at the end
  componentWillMount() {
    const { insertCss } = this.props.context;
    this.removeCss = insertCss(s);
    this.removeBootstrap = insertCss(bt);
  }
  • In componentWillUnmount function add this.removeBootstrap(); at the end
  componentWillUnmount() {
    this.removeCss();
    this.removeBootstrap();
  }

With this now you should be able to load correctly Bootstrap 3 without classNames renamed.

Was this page helpful?
0 / 5 - 0 ratings