ChatGPT解决这个技术问题 Extra ChatGPT

How to include bootstrap css and js in reactjs app?

I am new to ReactJS, I want to include bootstrap in my React app

I have installed bootstrap by npm install bootstrap --save

Now, want to load bootstrap CSS and JS in my React app.

I am using webpack.

webpack.config.js

var config = {
    entry: './src/index',

    output: {
        path: './',
        filename: 'index.js'
    },

    devServer: {
        inline: true,
        port: 8080,
        historyApiFallback: true,
        contentBase:'./src'
    },

    module: {
        loaders: [
            {
                test: /\.js?$/,
                exclude: /node_modules/,
                loader: 'babel',

                query: {
                    presets: ['es2015', 'react']
               }
            }
        ]
    }
};

module. exports = config;

My issue is “how to include bootstrap CSS and JS in ReactJS app from node modules?" How to set up for bootstrap to include in my React app?

Are you using Node.js on the backend?
Just import Bootstrap files in your HTML page
@DanielKhan : No, I am not using Node.js.
Are you using the less version of bootstrap or just the plain css? For the latter simply include the css using the CDN version and us react bootstrap for the JavaScript part.
@DanielKhan I have used plain css. I don't want to CDN. I want to use bootstrap from node_modules.

P
Praveen M P

If you are new to React and using create-react-app cli setup, run the npm command below to include the latest version of bootstrap.

npm install --save bootstrap

or

npm install --save bootstrap@latest

Then add the following import statement to index.js file. (https://getbootstrap.com/docs/4.4/getting-started/webpack/#importing-compiled-css)

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

or

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

don't forget to use className as attribute on target elements (react uses className as attribute instead of class).


Relative imports outside of src/ are not supported.
I dont get why not just link it in the html template
what about js files? jquery bootstrap.js
I found this article and it could be helpful blog.logrocket.com/how-to-use-bootstrap-with-react-a354715d1121
m
mhannani

Via npm, you would run the folowing

npm install bootstrap jquery --save
npm install css-loader style-loader --save-dev

If bootstrap 4, also add dependency popper.js

npm install popper.js --save

Add the following (as a new object) to your webpack config

loaders: [
    {
      test: /\.css$/,
      loader: 'style-loader!css-loader'
    }

Add the following to your index, or layout

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

One of the perfect up to date answer +1
For Bootstrap 5: yarn add @popperjs/core or npm i @popperjs/core
Can't resolve 'popper.js'
@blamb Can you explain why importing Bootstrap CSS at the top level makes it accessible in the child components?
S
Shota

You can't use Bootstrap Jquery based Javascript components in React app, as anything that tries to manipulate DOM outside React is considered bad practice. Here you can read more info about it.

How to include Bootstrap in your React app:

1) Recommended. You can include raw CSS files of Bootstrap as the other answers specify.

2) Take a look at react-bootstrap library. It is exclusively written for React.

3) For Bootstrap 4 there is reactstrap

Bonus

These days I generally avoid Bootstrap libraries which provide ready to use components (above-mentioned react-bootstrap or reactstrap and so on). As you are becoming dependent on the props they take (you can't add custom behavior inside them) and you lose control over DOM that these components produce.

So either use only Bootstrap CSS or leave Bootstrap out. A general rule of thumb is: If are not sure whether you need it, you don't need it. I've seen a lot of applications which include Bootstrap, but using the only small amount of CSS of it and sometimes the most of this CSS is overridden by custom styles.


With option 1), how do you include Bootstrap Javascript (and jquery)? Or you don't?
Unfortunately neither react-bootstrap or reactstrap support Bootstrap 4 yet.
"leave bootstrap out" is a pretty viable option. Great advice.
@Zim Now they do!
T
Thaadikkaaran

You can just import the css file wherever you want. Webpack will take care to bundle the css if you configured the loader as required.

Something like,

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

And the webpack config like,

loaders: [{ test: /\.css$/, loader: 'style-loader!css-loader' }]

Note: You have to add font loaders as well, else you would be getting error.


Thanks, for reply. Need any npm modules for style-loader and css-loader?
Yes use use style-loader css-loader loaders
Ok, now to look what is webpack (a little thing like include something and use it became into a horrible another js-thing to learn), ny aspirationw was to use a bootstrap3 style button in my tutorial app.... now I wouldn't
@J.Guarin if you are using Facebook's create-react-app it will set up webpack with style-loader for you.
D
Deekshith Anand

I too had a similar scenario. My setup was as indicated below

npm install create-react-app

This will provide you with a boiler-plate code setup to begin. Play around with the App.js file for the main logic.

Later you can use bootstrap CDN in index.html created by the CLI tool. or

npm install bootstrap popper jquery

and then simply include this in the App.js file.

import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap/dist/js/bootstrap.bundle'

Few authors have mentioned using className attribute instead of class, but in my case, both were working like below. But if you use class and look at console in developer tools on browser, you will see error for using class.So use className instead.

    <div className="App" class = "container"> //dont use class attribute

And don't forget to remove the default CSS imports to avoid conflicts with bootstrap.

Hope that helps, Happy coding!!!


This is the best answer for me. Also if you're using SCSS then load your own css instead of bootstrap's.
this has to be the accepted answer
A
Aditya Parmar

Please follow below link to use bootstrap with React. https://react-bootstrap.github.io/

For installation :

$ npm install --save react react-dom
$ npm install --save react-bootstrap

------------------------------------OR-------------------------------------

Put Bootstrap CDN for CSS in tag of index.html file in react and Bootstrap CDN for Js in tag of index.html file. Use className instead of class follow below index.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <link rel="shortcut icon" href="../src/images/dropbox_logo.svg">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">




  </head>
  <body>

    <div id="root"></div>

     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>

  </body>
</html>

The link you provided is dead
Hey David, Put Bootstrap CDN for CSS in tag of index.js file in react and Bootstrap CDN for Js in tag of index.js file. Use className instrad of class.
G
GavinBelson

Full answer to give you jquery and bootstrap since jquery is a requirement for bootstrap.js:

Install jquery and bootstrap into node_modules:

npm install bootstrap
npm install jquery

Import in your components using this exact filepath:

import 'jquery/src/jquery'; //for bootstrap.min.js
//bootstrap-theme file for bootstrap 3 only
import 'bootstrap/dist/css/bootstrap-theme.min.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.min.js';

I didn't need to import jquery, only install it with npm. I think bootstrap loads it by itself
In bootstrap 3, you need jquery loaded for some of the functionality
If you are using bootstrap 4.4.1, you will also need to also install popper.js npm module that is referred by 'bootstrap/dist/js/bootstrap.min.js'.
Good answer, ran into this problem with bootstrap 3 and using import 'jquery/src/jquery' instead of import 'jquery' fixed it
V
Vidhyapathi Kandhasamy

Hope this is helpful ;)

Step 1: using NPM install this bellow command

npm install --save reactstrap@next react react-dom

Step 2: example index.js main script import bellow command

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

Step 3: UI components refer bellow website reactstrap.github.io


Z
Zim

Bootstrap 5 (update 2021)

Bootstrap 5 is modular and no longer requires jQuery. Therefore, you can import Bootstrap components and reference them directly from bootstrap. This means you no longer need a 3rd-party library like react-bootstrap or reactstrap.

To use React + Bootstrap 5:

1_ install bootstrap and add it to package.json...

npm install 'bootstrap' --save

2_ import bootstrap and/or specific components...

import { Collapse, Popover, Toast, Tooltip, Alert, Modal, Dropdown } from bootstrap

3_ use a Bootstrap component. For example, here is the Dropdown...

// component
const DropdownDemo = () => {
    const ddRef = useRef()  

    useEffect(() => {
        var dd = new Dropdown(ddRef.current, {})
    })
    
    return (
        <div className="py-2">
            <div className="dropdown">
              <button className="btn btn-secondary dropdown-toggle" type="button" ref={ddRef} aria-expanded="false">
                Dropdown button
              </button>
              <ul className="dropdown-menu" aria-labelledby="dropdown1">
                <li><a className="dropdown-item" href="#">Action</a></li>
                <li><a className="dropdown-item" href="#">Another action</a></li>
                <li><a className="dropdown-item" href="#">Something else here</a></li>
              </ul>
            </div>
        </div>
    )
}

// React app
function App() {
  const [mounted, setMounted] = useState(true);

  return (
    <div>
        {mounted &&
            <div>
                <DropdownDemo />
            </div>
        }
    </div>
  )
}


Did you mean that I not need to include the following line if I am using bootstrap5 in my project? import 'bootstrap/dist/css/bootstrap.min.css';
I am sorry but i think this is a wrong answer, the modules of bootstrap are not compatible with react. At least I tried with react 18.2.0 and boostrap 5.1.3 and you can't import boostrap modules into react projects.
N
Nikhil
npm install --save bootstrap 

and add this import statement into your index.js file

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

or You could simply add CDN in your index.html file.


what about jquery?
@ValRob to add jquery to your project: npm i jquery --save then import $ from 'jquery'
M
Morteza Fathnia

I try with instruction:

npm install bootstrap
npm install jquery popper.js

then in src/index.js:

import 'bootstrap/dist/css/bootstrap.min.css';
import $ from 'jquery';
import Popper from 'popper.js';
import 'bootstrap/dist/js/bootstrap.bundle.min';
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<Dropdown />, document.getElementById('root'));
registerServiceWorker();

M
Majed HORIA

you can install it dirctly via

$ npm install --save react react-dom
$ npm install --save react-bootstrap

then import what you really need from the bootstrap like :

import Button from 'react-bootstrap/lib/Button';

// or

import  Button  from 'react-bootstrap';

and also you can install :

npm install --save reactstrap@next react react-dom

check this out click here .

and for the CSS you can read this link also carfuly

read here


Y
Yousuf Shaikh

After installing bootstrap in your project "npm install --save bootstrap@3.3.7" you have to move to the index.js file in the project SRC folder and import bootstrap from node module package.

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

If you like you can get help from this video, sure it will help you a lot.

Import Bootstrap In React Project


M
M Hasan Sunny

Here is how to include latest bootstrap
https://react-bootstrap.github.io/getting-started/introduction

1.Install

npm install react-bootstrap bootstrap

then import to App.js import 'bootstrap/dist/css/bootstrap.min.css'; Then you need to import the components that you use at your app, example If you use navbar, nav, button, form, formcontrol then import all of these like below:

import Navbar from 'react-bootstrap/Navbar'
import Nav from 'react-bootstrap/Nav'
import Form from 'react-bootstrap/Form'
import FormControl from 'react-bootstrap/FormControl'
import Button from 'react-bootstrap/Button'


// or less ideally
import { Button } from 'react-bootstrap';


The question is not about react-bootstrap. It's about bootstrap css framework. That means not this (react-bootstrap.github.io) but this one (getbootstrap.com)
w
wingman__7

Simple Solution (2020) is as follows :-

npm install --save jquery popper.js npm install --save bootstrap npm install --save style-loader css-loader update webpack.config.js, you've to tell webpack how to handle the bootstrap CSS files hence you've to add some rules as shown :-

https://i.stack.imgur.com/rq2xr.png

Add some imports in the entry point of your React Application (usually it's index.js), place them at the top make sure you don't change the order.

import "bootstrap/dist/css/bootstrap.min.css";

import $ from "jquery";

import Popper from "popper.js";

import "bootstrap/dist/js/bootstrap.bundle.min";

These steps should help you out, please comment if there's some problem.


p
prime

Just in case if you can use yarn which is recommended for React apps,

you can do,

yarn add bootstrap@4.1.1 // this is to add bootstrap with a specific  version

This will add the bootstrap as a dependency to your package.json as well.

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "bootstrap": "4.1.1", // it will add an entry here
    "react": "^16.5.2",
    "react-dom": "^16.5.2",
    "react-scripts": "1.1.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

After that just import bootstrap in your index.js file.

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

H
Hadi Mir

Since Bootstrap/Reactstrap has released their latest version i.e. Bootstrap 4 you can use this by following these steps

Navigate to your project Open the terminal I assume npm is already installed and then type the following command npm install --save reactstrap react react-dom

This will install Reactstrap as a dependency in your project.

Here is the code for a button created using Reactstrap

import React from 'react'; import { Button } from 'reactstrap'; export default (props) => { return ( ); };

You can check the Reactstrap by visiting their offical page


V
Vikram Gulia

Somehow the accepted answer is only talking about including css file from bootstrap.

But I think this question is related to the one here - Bootstrap Dropdown not working in React

There are couple of answers that can help -

https://stackoverflow.com/a/52251319/4266842 https://stackoverflow.com/a/54188034/4266842


a
ataman

If you use CRA(create-react-app) in your project, you can add this:

npm install react-bootstrap bootstrap

If you use bootstrap in your app and if it's not working, then use this in index.html :

<link
  rel="stylesheet"
  href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"
  integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS"
  crossorigin="anonymous"
/>

I did the above to solve similar problem. Hopefully this is useful to you :-)


I
Idhem

I just want to add that installing and importing bootstrap in your index.js file won't be enough for using bootstrap components. Every time you want to use a component you should import it, like: I need to use a container and a row

    <Container>
        <Row>
        <Col sm={4}> Test </Col>
        <Col sm={8}> Test </Col>
        </Row>
</Container>

You should import in your js file

import {Container, Row, Col} from 'react-bootstrap';

In the documentation the preferred way is to import each component individually. e.g. for Row it's import Row from 'react-bootstrap/Row'; Source: react-bootstrap.github.io/getting-started/…
J
Jafar Karuthedath

Here is what worked for me with bootstrap 4 with npm

Install jquery , popper.js, bootstrap packages npm install jquery popper.js bootstrap --save Update index.js with the following imports import "bootstrap/dist/css/bootstrap.min.css"; import "bootstrap/dist/js/bootstrap.js";

Additionally if you are using sass for your custom style, you can install sass package

npm install sass --save

M
Muhammad Ahmed

You can add the bootstrap by using visual studio terminal: YourApplicationName> npm install bootstrap@4.1.1