I am trying to import bootstrap 5.3.2 (not react-bootstrap) into a NextJS 14.1.0 project that uses new the new App Router. I would like to use individual BS components programmatically (not via data-attrs).
I got it to work but (I do get the tooltips) but I cannot get rid of this error 500 with each hard refresh. The console shows this exact message:
⨯ node_modules/bootstrap/dist/js/bootstrap.esm.js (803:18) @ document
⨯ ReferenceError: document is not defined
at __webpack_require__ (/Users/rsilva/Desktop/bs/.next/server/webpack-runtime.js:33:42)
at eval (./app/TooltipComponent.js:9:67)
at (ssr)/./app/TooltipComponent.js (/Users/rsilva/Desktop/bs/.next/server/app/page.js:162:1)
at __webpack_require__ (/Users/rsilva/Desktop/bs/.next/server/webpack-runtime.js:33:42)
Here’s my relevant code:
layout.js
import "bootstrap/dist/css/bootstrap.css";
import BootstrapProvider from "./providers/bootstrap";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body className="container my-5">
<BootstrapProvider/>
{children}
</body>
</html>
);
}
my BS provider (bootstrap.js):
"use client";
import { useEffect } from 'react';
function BootstrapProvider() {
useEffect(() => {
async function loadBootstrap() {
const bootstrap = await import('bootstrap/dist/js/bootstrap.bundle.min.js');
window.bootstrap = bootstrap;
}
loadBootstrap();
}, []);
return null;
}
export default BootstrapProvider;
page.js
import { TooltipComponent } from "./TooltipComponent";
export default function Home() {
return (
<main>
<TooltipComponent title="Test">
test tooltip
</TooltipComponent>
</main>
);
}
and finally the actual component that uses Tooltip programatically:
"use client";
import { useEffect, useRef } from "react";
import { Tooltip } from "bootstrap";
export function TooltipComponent({
children,
title = "Missing tooltip 'title' property",
placement = "top",
trigger = "hover",
}) {
const tooltipRef = useRef();
useEffect(() => {
if (title) {
const tooltip = new Tooltip(tooltipRef.current, {
title: title,
placement: placement,
trigger: trigger,
container: "body",
});
return () => {
tooltip.dispose();
};
}
}, [title]);
return <span ref={tooltipRef}>{children}</span>;
}
Any ideas? Thank you!
3
Answers
Why don’t you use react-bootstrap.
It provides bootstrap for react. You don’t have to create Boostrap Provider or link vanilla boostrap to window.
Example Tooltip
import the minified Bootstrap CSS file into the Next.js entry pages/_app.js file
Use the "Script" component to include "bootstrap/dist/js/bootstrap.bundle.min.js" js file in layout.js
Not needed Additional component.
Ref: https://nextjs.org/docs/pages/building-your-application/optimizing/scripts