When this fails server-side:
import * as Bootstrap from "bootstrap"
you can replace it with the following:
app/providers/bootstrap.js
"use client"
import React, { createContext, useContext, useEffect, useState } from "react"
const Context = createContext(undefined)
function Providers({ children } {
const [Bootstrap, setBootstrap] = useState(undefined)
useEffect(() => {
if (!Bootstrap) {
const BS = require("bootstrap/dist/js/bootstrap.bundle.min.js")
setBootstrap(BS)
}
}, [])
return (
<Context.Provider value={{ Bootstrap }}>
{children}
</Context.Provider>
)
}
export const useBootstrap = () => {
const context = useContext(Context)
if (context === undefined) {
throw new Error("useBootstrap must be used inside BootstrapProvider")
}
return context
}
export default Providers
app/layout.tsx
import "bootstrap/dist/css/bootstrap.min.css"
import "../styles/_global.scss"
import { Metadata } from "next"
import BootstrapProvider from "@/providers/bootstrap"
export const metadata: Metadata = {}
export default function RootLayout({ children }) {
return (
<html>
<body>
<BootstrapProvider>
{children}
</BootstrapProvider>
</body>
</html>
)
}
and use it like this in the client-side component:
app/components/CollapsibleExample.js
"use client"
import { useBootstrap } from "@/providers/bootstrap"
export default () => {
const { Bootstrap } = useBootstrap()
const toggle = (event) => {
event.preventDefault()
new Bootstrap.Collapse(`#collapse-id`).toggle()
}
return (
<a href="#" onClick={toggle}>Toggle</a>
)
}