Skip to content Skip to sidebar Skip to footer

How Can I Use Bootstrap 5 With Next.js?

After installing bootstrap with npm install bootstrap I added the style to /pages/_app.js like so: import 'bootstrap/dist/css/bootstrap.css'; export default function App({ Componen

Solution 1:

This is a common thing that most of us miss while switching to NextJS.

Problem: Document is not defined.

Reason: NextJS renders your app at server, and there is no window, document etc. on server, hence document is not defined. you can even console.log(typeof window, typeof document) to verify this.

enter image description here

NOW, what is the solution?

I used this code in my function component:

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

useEffect with empty dependencies works like componentDidMount() which runs after the code is run second time. Since code runs first at server and then at client, it will not produce errors, as client has document.

I've never used `componentDidMount(), ever.

Did that worked for me?

I just copied your Collapse example in my other app to verify this.

enter image description here


Solution 2:

I believe React Bootstrap (beta as of July 2021) now supports Bootstrap5: https://react-bootstrap.github.io/ See image from their website:

From their website


Solution 3:

the _app.js and _app.tsx are difference

function MyApp({ Component, pageProps }: AppProps) {
  // import bootstrap-js-libs below for _app.js
  useEffect(() => {
     import("bootstrap/dist/js/bootstrap");
   }, []);

  useEffect(() => {
    typeof document !== undefined ? require("bootstrap/dist/js/bootstrap") : null;
  }, []);

We can use CDN on _document file too!


Solution 4:

You only imported bootstrap.css, you must import bootstrap's js file if you want to use collapse. And bootstrap's js require jquery and popper. However, react or nextjs doesn't recommend you to use jquery.

You can use one of 2 below libs alternative:

  1. react-bootstrap
  2. reactstrap

For latest bootstrap 5, you can use BootstrapCDN:

In _document.js, add 2 lines:

<link  href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" integrity="undefined" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js" integrity="undefined" crossorigin="anonymous"></script>

Post a Comment for "How Can I Use Bootstrap 5 With Next.js?"