Using modular CSS with Bootstrap 4 and React

Tom picture Tom · May 1, 2016 · Viewed 7.2k times · Source

I've enabled postCSS with ModularCSS and webpack:

{
  test: /\.css$/,
  exclude: /node_modules/,
  loader: "style-loader!css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss-loader"
}

This means that I can now import "CSS Modules" like so:

components/app.js

import '../style/bootstrap.css';

This will ensure that the entire app is based on bootstrap's "global css", like resetting.

Furthermore, within components I can clearly define their dependencies on Bootstrap, e.g.:

components/control.js

import Bootstrap from '../style/bootstrap.css';

class Control extends Component {

  render() {
    return (
      <button className={Bootstrap.btn + ' ' + Bootstrap['btn-primary']}>choose me</button>
    );
  }
}

However, the syntax className={Bootstrap.btn + ' ' + Bootstrap['btn-primary']} is hard to read and not easy to work with.

Has this issue been tackled before? Any suggestions on how to make it more readable and workable?

Answer

QoP picture QoP · May 1, 2016

You could try to use classNames

import Bootstrap from '../style/bootstrap.css';

let cx = classNames.bind(Bootstrap);


class Control extends Component {

  render() {
    let className = cx({
      btn: true,
      'btn-primary': true
    });
    return (
      <button className={className}>choose me</button>
    );
  }
}