Having trouble getting the Bootstrap Dropdown to function properly in the Navbar while using NextJs

I am having an issue where the Dropdown menu is not opening up when clicked. I am currently using bootstrap 5 on nextjs 12.

I attempted to add the CDN links, but unfortunately, it was not successful.

Any assistance or advice would be greatly appreciated.

In my app.js file, I imported bootstrap.css:

_app.js

import "../styles/globals.css";
import "bootstrap/dist/css/bootstrap.css";

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

export default MyApp;

In the Index.js file, I included the CDN link:

index.js

import Head from "next/head";
import Footer from "../components/Footer";
import Header from "../components/Header";
import Script from "next/script";

export default function Home() {
  return (
    <main className="d-flex flex-column min-vh-100">
      <Header />
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"></link>
      </Head>
      <Script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" />
      <div className="px-4 py-5 my-5 text-center flex-grow-1">
        <h1 className="display-5 fw-bold">Next.js + Bootstrap ❤️</h1>
       
      </div>
      <Footer />
    </main>
  );
}

Header.js

const Header = () => {
  return (
    <header className="p-3 bg-dark text-white">
      <div className="container">
        <div className="d-flex  flex-wrap align-items-center justify-content-center justify-content-lg-start ">
         <ul className="nav col-12 col-lg-auto ms-lg-auto mb-2 justify-content-center mb-md-0  "> 
            <li className="nav-item dropdown">
              <a href="#" className="nav-link px-2 text-white dropdown-toggle">
                Services
              </a>
              <div className="dropdown-menu">
                <a href="#" className="dropdown-item">
                  React
                </a>
                <a href="#" className="dropdown-item">Test</a>
              </div>
            </li>      
          </ul>
        </div>
      </div>
    </header>
  );
};
export default Header;

Answer №1

Learn how to implement a navbar with bootstrap in your React or Nextjs project by following this informative tutorial

Avoid using CDN links for bootstrap when integrating a navbar into your React project

You can utilize the React bootstrap framework to easily add a navbar

npm install react-bootstrap bootstrap

Include the stylesheet in your app.js file as shown below

import 'bootstrap/dist/css/bootstrap.min.css';

Follow the code snippet provided to create a navbar component:

import Container from 'react-bootstrap/Container';
import Nav from 'react-bootstrap/Nav';
import Navbar from 'react-bootstrap/Navbar';
import NavDropdown from 'react-bootstrap/NavDropdown';

function BasicExample() {
  return (
    <Navbar bg="light" expand="lg">
      <Container>
        <Navbar.Brand href="#home">React-Bootstrap</Navbar.Brand>
        <Navbar.Toggle aria-controls="basic-navbar-nav" />
        <Navbar.Collapse id="basic-navbar-nav">
          <Nav className="me-auto">
            <Nav.Link href="#home">Home</Nav.Link>
            <Nav.Link href="#link">Link</Nav.Link>
            <NavDropdown title="Dropdown" id="basic-nav-dropdown">
              <NavDropdown.Item href="#action/3.1">Action</NavDropdown.Item>
              <NavDropdown.Item href="#action/3.2">
                Another action
              </NavDropdown.Item>
              <NavDropdown.Item href="#action/3.3">Something</NavDropdown.Item>
              <NavDropdown.Divider />
              <NavDropdown.Item href="#action/3.4">
                Separated link
              </NavDropdown.Item>
            </NavDropdown>
          </Nav>
        </Navbar.Collapse>
      </Container>
    </Navbar>
  );
}

export default BasicExample;

Answer №2

Step 1: Add Bootstrap CSS to your _app.js

import "bootstrap/dist/css/bootstrap.min.css";

Step 2: Include Bootstrap JS in your _app.js

import { useEffect } from "react";

useEffect(() => {
    require("bootstrap/dist/js/bootstrap.bundle.min.js");
  }, []);

The final code should look like this:

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

config.autoAddCss = false;

export default function App({ Component, pageProps }) {
  
  useEffect(() => {
    require("bootstrap/dist/js/bootstrap.bundle.min.js");
  }, []);

  return <Component {...pageProps} />
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Avoiding conflicts in user registration with Firebase

I'm currently working on a Firebase/Next.js application deployed via Firebase hosting. In this project, I am focused on developing a user registration feature. When a new user registers, they are assigned a document containing their data, with one of ...

Implementing React with Tailwind and AOS to Enhance User Experience

I recently utilized the React Tailwind template to develop a website. It functions flawlessly in my browser with no issues when running npm start. However, I encountered errors while attempting to deploy it on Netlify or Heroku despite following the docume ...

Is there a way to activate the onClick event in Reactjs within the render method rather than the

Is it possible to assign an onClick function when performing a conditional render outside of the React return statement? I tried adding code on Stackoverflow but couldn't get any syntax help or eslint after spending an hour in their editor. :D sec ...

Why is the click function being invoked twice, but exclusively on the initial click?

In my current project, I am facing an issue with the onClick action that is being passed down from Context. Strangely, when this action is clicked for the first time, it fires twice. However, from the second click onwards, it functions normally and only fi ...

Making an AJAX call in React JS

I'm currently in the process of creating a dashboard application using reactredux. Coming from an angular background, I find myself feeling a bit lost here. What I need help with is figuring out how to fetch data from an API to display in graphs on th ...

TypeScript is failing to identify a correctly typed property

Currently, I am facing issues while converting a Material UI Dashboard from React to Typescript. The problem arises during TypeScript compilation where the property in question meets the criteria mentioned in the error message. To put it briefly, the compi ...

Users are unable to modify Blockly's text block input fields within a Material-UI Modal

After scouring through various resources, I stumbled upon a Google Groups thread at this link. Unfortunately, the thread lacked any answers that could assist me. To address this issue, I decided to create a Codesandbox to replicate the problem. You can ac ...

Creating a Back Handler in a React Native Stack Navigator for seamless navigation

Is there a way in React Native Stack Navigator to navigate back to previous pages from some screens and disable the ability to go back from others? I've tried using Back Handler, but it doesn't seem to be working. How can I achieve this functiona ...

Ways to determine the number of duplicate items in an Array

I have an array of objects that contain part numbers, brand names, and supplier names. I need to find a concise and efficient way to determine the count of duplicate objects in the array. [ { partNum: 'ACDC1007', brandName: 'Electric&apo ...

My approach to using this style in React involves utilizing the class attribute as follows: "class[attribute]" [Updated version 2]

When trying to customize an element based on its attribute, the process is a bit different in React compared to pure CSS. Here's an example: <div class='something' data-test='4'></div> ... .something[data-test] { bac ...

Customize the disabled styles for InputBase in Material UI

Struggling to figure out how to override the given rule on an InputBase: .MuiInputBase-root.Mui-disabled { color: rgba(0, 0, 0, 0.38); } The desired rule is: color: "rgba(0, 0, 0, 0.75)" Tried using classname and classes without success. Any suggest ...

Refreshing the child component based on the child's action and sending information to the parent in a React application

Within my Parent Component, I am utilizing an Ajax call to populate two children Components. C1 requires the data only once, while C2 has the ability to fetch additional data through subsequent Ajax calls and needs to render accordingly. I find it more co ...

Design distinctive components using Material UI's styling feature

Currently, I have integrated the NumberFormat package from here, but my goal is to customize its style to match a TextField component from material-ui. This is how my component looks like: <NumberFormat label={strings.minDays} style={{marginRight:&apo ...

Adding labels to a JavaScript chart can be done by using the appropriate methods

https://i.stack.imgur.com/uEgZg.png https://i.stack.imgur.com/y6Jg2.png Hey there! I recently created a chart using the Victory.js framework (check out image 1) and now I'm looking to incorporate labels similar to the ones shown in the second image ab ...

Tips for dynamically incorporating points such as "..." to signify additional pagination buttons during web development

Can someone help me add a "..." between pagination buttons if there are more than five buttons in my code? Here is the current pagination script I have: import React, { useState } from 'react' const Pagination = ({productsPerPage, totalPosts, p ...

Capture all URLs containing [...slug] and generate static props only for valid addresses in Next.js

I am utilizing dynamic routes with the fallback:true option to ensure newly created pages are accepted. First, I check if the parameters are true, then I create related props and display the component with those props. In the console, I can observe that Ne ...

Struggling to share information across components in React

I am currently working on developing a Weather app to enhance my React skills, but I am facing some challenges. You can access the code I have written here: Codesandbox My project consists of 3 components: Form.jsx Weather.jsx WeatherDetail.jsx Weather. ...

Ran into a pair of kids sharing the same key - result in duplicate items

I have a multi-language page in NextJS and I want to implement language selection through a dropdown menu. const languages = [ { locales: 'fa', name: 'فارسی', country_code: 'ir' }, { locales: 'e ...

Tips on enhancing the appearance of your numberbox with vibrant colors

Hello everyone! I am working with some devextreme code blocks and need help in changing the border color of a numberbox to red. Can anyone guide me on how to achieve this? import React, { useState } from 'react'; import { NumberBox } from 'd ...

Step-by-step guide on redirecting to a different page in NextJS if a dynamic route cannot be found

I need assistance with redirecting users when they access a dynamic route that does not exist. The dynamic route points to a field within a statically defined array of fields. Here is the code snippet for the page: import { fields } from "@/data/fiel ...