Home > other >  How can I use bootstrap 5 Javascript in my Next JS app?
How can I use bootstrap 5 Javascript in my Next JS app?

Time:01-12

This is my first experience with Next JS and I am trying to bootstrap the Next JS app, which has been going on well until now that I have to use bootstrap's Javascript for a carousel.

So first, I added the bootstrap js to the script of the next js page (pages/gallery/[id].js) manually like this:

import Script from "next/script";
import Layout from "../../layouts/interface";
import SlidingComponent from "../../components/slide";

export default function GalleryPage() {
    const router = useRouter();
    const {id} = router.query;

  return (
    <Layout>
    <SlidingComponent />

   <Script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg OMhuP IlRH9sENBO0LRn5q 8nbTov4 1p" crossorigin="anonymous" />
    </Layout>
  )
}

This works initially but as soon as the second slide image comes in, next js throws the following error:

Unhandled Runtime Error
TypeError: Cannot read properties of null (reading 'classList')

Call Stack
st._setActiveIndicatorElement
https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js (6:13913)
st._slide
https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js (6:15057)
st.next
https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js (6:10814)
st.nextWhenVisible
https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js (6:10883

I found another way to correct the error online. It says I should import the bootstrap js in my pages/_app.js like this:

import 'bootstrap/dist/css/bootstrap.css'
import '../styles/globals.css'
import {useEffect} from "react";

//this is what the solution says:
useEffect(() => {
    import("bootstrap/dist/js/bootstrap");
}, []);

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

export default MyApp

But this too gives me the following error:

https://nextjs.org/docs/messages/module-not-found
wait  - compiling...
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

Now I don't even know what to do, can anybody please help me?

CodePudding user response:

Use Approach 2, for the popperjs error follow these steps

npm i @popperjs/core

  •  Tags:  
  • Related