In a freshly created Next.js app, install Bootstrap npm i bootstrap
. Over in layout.js
, import the bootstrap.css file, import 'bootstrap/dist/css/bootstrap.min.css';
and comment out globals.css
.
I've replaced Next.js' boilerplate with a Navbar from Bootstrap's website. This Navbar has a couple of tags that aren't closed. Once you do that, it will work perfectly.
On the dev server, our styles are there but the hamburger menu doesn't work until we import Bootstrap's JS file. in components/BootstrapClient.js
, create a client component using "use client"
, import { useEffect } from 'react'
, and create the BootstrapClient component. Inside that component, add the Bootstrap import inside of the useEffect.
AN IMPORTANT NOTE: If you’re using the pages directory, you don’t have to use a Client Component. You can add in the useEffect right above the return statement and import the bootstrap file there.
Now, it should all be working!
Transcript
Bootstrap is a widely popular front-end toolkit used for styling websites. It's so popular because of its easy-to-implement grid system, allowing you to place elements exactly where you need.
Along with the grid system, it allows you to create easily responsive designs using its predetermined breakpoints and infixes. Today, I'll show you how to install and start using Bootstrap in a Next.js application.
In a freshly created Next.js app, run npm i bootstrap to install the latest version. Then in layout.js, underscore app.js if you're using the pages directory, import the bootstrap styling sheet, and comment out the global CSS import.
Back in pages.js and Next.js if you're using the pages directory, we can start developing using Bootstrap. I'll remove this boilerplate and paste in a navbar from Bootstrap's site. This has a couple of small edits in it to fix some tags that weren't closed.
Start the server with npm run dev and head over to our local host. We now see a navbar created by Bootstrap. But when we resize the screen and hit our hamburger menu, it highlights but it doesn't drop down. That's because we need Bootstrap's JS file.
To import Bootstrap's JS file, start by creating a folder to hold our components, and create a file called bootstrap-client.js.
This will need to be a client component, so start the file with use client and import use effect from React.
To create the bootstrap-client component, export default function bootstrap-client,
add in the use effect, and in here import the bootstrap file we need.
Back over in layout.js, import that client component, and add it just below the body tag.
An important note, if you're using the pages directory, you don't have to use a client component. You can add in the use effect right above the return statement in this file and import the bootstrap file there. Double check to see if our hamburger menu is working, and it is!
Now, with Bootstrap up and running, you can move on to designing your website.