How to add bootstrap js in a Gatsby Website

Fixed this by adding my bootstrap dependencies in gatsby-browser.js (if it is not present in your project add it in your root directory by creating a fresh file with the same name gatsby-browser.js).

First, I installed the dependencies using npm:

npm install bootstrap jquery @popperjs/core

And, here is how I have added in gatsby-browser.js:

import './src/sass/app.scss'
import 'jquery/dist/jquery.min.js'
import 'popper.js/dist/popper.min'
import 'bootstrap/dist/js/bootstrap.min.js'

app.scss is the file where I have imported my bootstrap components along with my custom styles.

Alternatively, you can use react-bootstrap which removes the unnecessary jQuery dependency for bootstrap but uses bootstrap styling to style its own component.

UPDATE

The popper.js has been deprecated and now it can be found here

Thanks, Ben for pointing it out,

UPDATE [May 2021]:

Bootstrap released v5 on 5th May 2020, so those who are working with Bootstrap v5 should follow these instructions.

In Bootstrap v5. Bootstrap is migrating from 1.x.x to 2.xx popper.js and therefore :

Step 1: First change the Bootstrap version: npm i bootstrap@next

Step 2: Update Popper.js to v2 npm i @popperjs/core

Step 3: In gatsby-browser.js add the following imports

import "bootstrap/dist/css/bootstrap.min.css";
import "bootstrap/dist/js/bootstrap.min.js";
import "@popperjs/core/dist/umd/popper.min.js";

[Almost similar as the accepted answer.]

Another way to add Bootstrap and related dependency with gatsby is adding them in gatsby-browser.js like following:

Step 1: Run npm i bootstrap jquery popper.js

Step 2: In gatsby-browser.js add following imports

import "bootstrap/dist/css/bootstrap.min.css";
import "jquery/dist/jquery.min.js";
import "popper.js/dist/popper.min";
import "bootstrap/dist/js/bootstrap.min.js";

Note: if gatsby-browser.js is already present and contains ES5 code, then that needs to converted to ES6 first

UPDATE [Jan 2021]:

After the Bootstrap v5.0.0; these steps have changed because Bootstrap's migration from 1.x.x to 2.xx Popper.js and complete removal of JQuery:

Now the steps are: Step 1: First change the Bootstarp version t0 5: npm i bootstrap@^5.0.0

Step 2: Update Popper.js to v2 npm i @popperjs/core@^2.5.4

Step 3: In gatsby-browser.js add the following imports

import "bootstrap/dist/css/bootstrap.min.css";
import "bootstrap/dist/js/bootstrap.min.js";
import "@popperjs/core/dist/umd/popper.min.js";

To use react-bootstrap

STEP 1:

npm install react-bootstrap bootstrap

STEP 2: Load your bootstrap in gatsby-browser.js

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

If you don't have a gatsby-browser.js, create gatsby-browser.js in your root folder and add the above snippet

Also, I had to restart my server for it to reflect in gatsby development server

ref: https://react-bootstrap.github.io/getting-started/introduction/