How to Correctly Use Bootstrap 5 in Next.js

Last updated on August 31, 2021 A Goodman Loading... 25 comments

This article shows you how to correctly use Bootstrap 5 in a Next.js project. By the end of this article, we will be able to:

  • Use all CSS classes provided by Bootstrap 5 whereever you want.
  • Use all Javascript functionality provided by Bootstrap 5 without errors.

Without any further ado, let’s get our hands dirty.

The Steps

Installing

You can add Bootstrap 5 to your Next.js project by executing the following command:

npm i bootstrap

Adding CSS

To use the styles from Bootstrap, we need to manually import its CSS file into the pages/_app.js file (create one if it doesn’t exist) :

import 'bootstrap/dist/css/bootstrap.css'; // Add this line
import '../styles/globals.css'

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}

export default MyApp

At this point, you are ready to use Bootstrap’s CSS features, like this:

<button className="btn btn-primary m-3">Button Primary</button>

However, components that need Javascript like dropdown, collapse, accordion, carousel... will NOT work and will cause errors even if you import Bootstrap’s Javascript file like this:

import "bootstrap/dist/js/bootstrap";

To fix this, we have to do an extra step.

Using Javascript features

Bootstrap uses some only-client-side objects (window, document) to handle events. On the other hand, Next.js renders the app on both the server-side and client-side. There is no window, document on the server-side thus you can see some error messages like the following:

document is not defined
windows is not defiend

To avoid the mentioned errors, we have to make sure that the window and document objects only be used on the client side. That can be done with the useEffect hook:

// Place this in the pages/_app.js file
useEffect(() => {
    import("bootstrap/dist/js/bootstrap");
}, []);

For more clarity, see the complete example below.

The Example

Preview

In this demo, we have some beautiful buttons made with Bootstrap. The dropdown select button is a thing that needs Javascript to work.

The Code

1. pages/_app.js:

import "bootstrap/dist/css/bootstrap.css";
import "../styles/globals.css";

import { useEffect } from "react";

function MyApp({ Component, pageProps }) {
  useEffect(() => {
    import("bootstrap/dist/js/bootstrap");
  }, []);

  return <Component {...pageProps} />;
}

export default MyApp;
// KindaCode.com

2. pages/index.js:

// KindaCode.com
export default function Home() {
  return (
    <div className="container p-3">
      <button className="btn btn-primary m-3">KindaCode.com</button>
      <button className="btn btn-warning m-3">Hello</button>

      <div className="dropdown m-3">
        <button
          className="btn btn-secondary dropdown-toggle"
          type="button"
          data-bs-toggle="dropdown"
          id="dropdownMenuButton1"
          aria-expanded="false"
        >
          Dropdown button
        </button>
        <ul className="dropdown-menu" aria-labelledby="dropdownMenuButton1">
          <li>
            <a className="dropdown-item" href="#">
              Option 1
            </a>
          </li>
          <li>
            <a className="dropdown-item" href="#">
              Option 2
            </a>
          </li>
          <li>
            <a className="dropdown-item" href="#">
              Option 3
            </a>
          </li>
        </ul>
      </div>
    </div>
  );
}

Conclusion

You’ve learned how to fully use Bootstrap 5 in a Next.js project. If you’d like to explore more new and interesting stuff about modern frontend development with Next.js and React, take a look at the following articles:

You can also check our React topic page and Next.js topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
25 Comments
Inline Feedbacks
View all comments
Mahafuzu
Mahafuzu
1 month ago

Thanks you saved me

Pablo
Pablo
1 month ago

Gracias

Tahsin Ahmed
Tahsin Ahmed
2 months ago

Thanks, man!!!

Rod
Rod
2 months ago

Is great. Thanks

Ashwin
Ashwin
2 months ago

Thanks you for the article. Really helped

YuZo
YuZo
3 months ago

This infomation is very useful to me !! Thanks

RodZadra
RodZadra
4 months ago

This information help me too much! I tryed to run tw-elements in NextJS without success before!

farshid
farshid
4 months ago

if you are using typescript. do this for js part:

useEffect(() => {
  typeof document !== undefined 
  ? require('bootstrap/dist/js/bootstrap') 
  : null
}, [])
Shahab Matapour
Shahab Matapour
5 months ago

./node_modules/next/dist/build/webpack/loaders/css-loader/src/index.js??ruleSet[1].rules[2].oneOf[9].use[1]!./node_modules/next/dist/build/webpack/loaders/postcss-loader/src/index.js??ruleSet[1].rules[2].oneOf[9].use[2]!./node_modules/next/dist/build/webpack/loaders/resolve-url-loader/index.js??ruleSet[1].rules[2].oneOf[9].use[3]!./node_modules/next/dist/compiled/sass-loader/cjs.js??ruleSet[1].rules[2].oneOf[9].use[4]!./node_modules/bootstrap/scss/bootstrap.scss Cannot find module ‘sass’ Require stack: – F:\host\NextJs\Germany\deutsch-frontend\node_modules\next\dist\compiled\sass-loader\cjs.js –

Thanks for your article I did it step to step but I encounter with above error. Would you please tell me how to solve it ?

Juan
Juan
5 months ago

Good job! how supposed to know that?

Thank you! Really.

Dev
Dev
5 months ago

manyyyyy thanks

sl-user
sl-user
5 months ago

Man, thank you!

leo
leo
6 months ago

Thanks

Manuel Avelar
Manuel Avelar
7 months ago

I got this error

error - ./node_modules/bootstrap/dist/js/bootstrap.js:7:0
Module not found: Can't resolve '@popperjs/core'

Import trace for requested module:
./pages/_app.js

Manuel Avelar
Manuel Avelar
7 months ago
Reply to  A Goodman

Yes, fixed, Thanks!

Bappy
Bappy
7 months ago

Thank you.

Toseef Zafar
Toseef Zafar
7 months ago

Thanks!

El pijudo
El pijudo
7 months ago

thanks man !

Jason
Jason
9 months ago

Thank you!!

Hooppy
Hooppy
1 month ago
Reply to  A Goodman

Please, can you show an example on how to use modal with this bootstrap?

I can’t import Modal in server-side.

I want to do lke this:

const modal = new Modal(‘some_id’)

but i can’t, it give error on server side while importing Modal component (or it is function..)

Nextjs Learner
Nextjs Learner
10 months ago

thanks it works

Related Articles