Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In React how to import only needed Bootstrap styles. Bootstrap css modules?

I want to use bootstrap 4 in my React project. The built css file should have only styles of bootstrap classes that I included in my React components.

I am not searching for Bootstrap css classes as React components; I don't mind to write <div className='container'>

1. Reactstrap

I tried with reactstrap, and yes has bootstrap css classes as components (e.g <Container></Container>) but you have to includes all bootstrap styles:

In src/index.js:

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

2. Scss source files

Because I already had sass-loader I tried importing directly the scss file:

import bootstrapGrid from 'bootstrap/scss/_grid.scss';
const myComponent = () => <div className={bootstrapGrid.container}>[...]</div>

But it fails as it doesn't have enough data to compile:

enter image description here

3. Oher solutions:

  • react-bootstrap I don't need js logic in react way (and it is v3)
  • styled-bootstrap still too new
  • bootstrap-css-modules seems good, but it is unmaintained

What is the right direction?

Or should I go for purifycss-webpack to clean up my App? And remove unused css classes.

like image 775
Mikel Avatar asked Feb 09 '18 14:02

Mikel


1 Answers

You can do the following which should include all the necessary modules to compile just the grid:

import bootstrapGrid from 'bootstrap/scss/bootstrap-grid.scss';

Or, include variables first & all other modules that are needed to compile the grid:

import bootstrapFunctions from 'bootstrap/scss/_functions';
import bootstrapVariables from 'bootstrap/scss/_variables';
import bootstrapMixinBreakpoints from 'bootstrap/scss/mixins/_breakpoints';
import bootstrapMixinGridFramework from 'bootstrap/scss/mixins/_grid-framework';
import bootstrapMixinGrid from 'bootstrap/scss/mixins/_grid';
import bootstrapGrid from 'bootstrap/scss/_grid.scss';
import bootstrapUtilitiesDisplay from 'bootstrap/scss/utilities/_display';
import bootstrapUtilitiesFlex from 'bootstrap/scss/utilities/_flex';

You can check which modules are needed from the bootstrap-grid.scss file @imports:

@import "functions";
@import "variables";

@import "mixins/breakpoints";
@import "mixins/grid-framework";
@import "mixins/grid";

@import "grid";
@import "utilities/display";
@import "utilities/flex";
like image 62
Syden Avatar answered Sep 23 '22 20:09

Syden