Mikel
Mikel

Reputation: 6232

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:

What is the right direction?

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

Upvotes: 6

Views: 7824

Answers (1)

Syden
Syden

Reputation: 8625

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";

Upvotes: 3

Related Questions