Troubleshooting a dysfunctional collapsed navbar in React with Bootstrap 5

I am experiencing an issue where the collapsed navbar icon does not expand when clicked on smaller screens. I followed the example provided by bootstrap 5 and made sure to include bootstrap css/js and jquery.

class CustomNavBar extends Component {
    render() {
      return (
        <div className="CustomNavBar">
            <nav className="navbar navbar-expand-lg navbar-dark bg-dark">
                <div className="container-fluid">
                    <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
                      <span className="navbar-toggler-icon"></span>
                    </button>
                    <div className="collapse navbar-collapse" id="navbarNavAltMarkup">
                      <div className="navbar-nav mx-auto">
                        <HashLink className="navbar-brand" to="/#app">
                            Site
                        </HashLink>
                        <HashLink className="nav-link" to="/#about">
                            About
                        </HashLink>
                        <HashLink className="nav-link" to="/#skills">
                            Skills
                        </HashLink>
                        <HashLink className="nav-link" to="/#experience">
                            Experience
                        </HashLink>
                        <Link className="nav-link" to="/calculator">
                            Calculator
                        </Link>
                      </div>
                    </div>
                </div>
            </nav>
        </div>
      );
    }
}

Answer №1

We encountered an issue due to the absence of the bootstrap js file in our codebase. To rectify this problem, it is imperative that we include the following line of code in the App.js file:

import 'bootstrap/dist/js/bootstrap.bundle';

Answer №2

I came across a solution that uses react hooks for toggling Bootstrap navbar collapse button: https://dev.to/johnotu/how-to-toggle-bootstrap-navbar-collapse-button-in-react-without-jquery-joo

import React, { useState } from 'react';
import Logo from '../images/logo_512x512.png';

const TopNav = props => {
  const [isNavCollapsed, setIsNavCollapsed] = useState(true);

  const handleNavCollapse = () => setIsNavCollapsed(!isNavCollapsed);

  return (
    <nav class="navbar navbar-expand-lg navbar-light bg-light rounded">
      <a class="navbar-brand text-info font-weight-bolder" href="/">
        <img src={Logo} alt="Logo" width="36" height="36" className="vertical-align-middle" />
        <span className="">Discounter</span>
      </a>
      <button class="custom-toggler navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample09" aria-controls="navbarsExample09" aria-expanded={!isNavCollapsed ? true : false} aria-label="Toggle navigation" onClick={handleNavCollapse}>
        <span class="navbar-toggler-icon"></span>
      </button>

      <div class={`${isNavCollapsed ? 'collapse' : ''} navbar-collapse`} id="navbarsExample09">
        <a className="nav-link text-info" href="/contact">Support</a>
        <a className="nav-link text-info" href="/login">Login</a>
        <a href="/request-demo" className="btn btn-sm btn-info nav-link text-white" >Request demo</a>
      </div>
    </nav>
  );
}

export default TopNav;

Answer №3

After encountering the same challenges, I successfully resolved them by incorporating -bs into data-toggle and data-target, transforming them into data-bs-toggle and data-bs-target respectively.

These are the dependencies listed in my package.json:

  • "bootstrap": "^5.2.0",
  • "jquery": "^3.6.0",
  • "popper.js": "^1.16.1",
  • "react": "^18.2.0",
  • "react-dom": "^18.2.0",

Below is an example code snippet illustrating the change made:

Original Code

   <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>

Amended Code

<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>

Answer №4

Make sure to add the following line of code for importing. import 'bootstrap/dist/js/bootstrap.bundle';

<nav class="navbar navbar-expand-lg navbar-light bg-light">
Navigation Bar Home Link Dropdown
  • Action
  • Another action
  • Something else here
  • Disabled Search

    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

    Guide to retrieving and showing specific items from a DropDownList in a Text box using JavaScript, HTML, and AngularJS

    Can someone explain how to extract and select items from a DropDownList and display them in a Textbox using JavaScript/HTML/AngularJS? Here are more details: I have a dropdown list with many items. When I click on an item from the list, it should be dis ...

    What is the optimal frequency for saving data when dealing with a particularly extensive form?

    I am facing a challenge with saving data to the database using Ajax. While I can handle this aspect, my difficulty lies in the fact that I have a very extensive form that is nested and cannot be altered. This large form consists of approximately 100 input ...

    Check if the string contains any numerical characters

    Is there a way to check if a string contains at least one numerical character without verifying if the entire string is a number? The current code works in the following situations: If there is a single integer, such as "43", it will display the correspon ...

    Using JavaScript parameters in a HTML document

    I am trying to replicate a page similar to this. The issue I am facing is the inability to use external JS files in ASP.net (as far as I know). Therefore, I am defining the functions and attempting to utilize them within the HTML page instead. <%@ P ...

    Creating a circular shape with a radius that can be adjusted

    I'm trying to create an expanding bubble-like circle of various colors when clicked on a blank page. The circle should continue increasing in size each time it is clicked, only stopping when the mouse click is released. I am looking to use HTML, CSS, ...

    Creating a dynamic table based on selected dropdown option

    I need to create a dynamic table of questions depending on the user's selection from a dropdown menu. When the user chooses a category, I want to pass that information to an API using the GET method. My controller is built using AngularJS. However, I ...

    Learn a valuable trick to activate CSS animation using a button - simply click on the button and watch the animation start over each time

    I already know how to do this once. However, I would like the animation to restart or begin again when the user clicks on it a second time. Here is what I have: function animation() { document.getElementById('ExampleButton').className = &apo ...

    The CSS class is not functioning properly while the ID is working perfectly

    A question I have pertains to the navigation menu on my website and its default styling... <nav> <ul id="MenuBar1" class="MenuBarHorizontal"> <li> <a href="#">Home</a> </li> <li> <a class="Menu ...

    What is the more effective choice for Automation Testing: Static or Dynamic dropdown menu options?

    Currently facing an issue with dropdown selections while conducting automated testing. Selenium's Select(); method has been reliable when running tests in multiple cycles and choosing different options each time. The challenge arises when the dropdow ...

    The art of positioning images and creatively cropping

    Seeking advice on allowing users to dynamically position and clip an image on a webpage. I've tried using CSS and JavaScript for clipping and resizing, but it's not working as expected. If PHP could provide a solution, that would be ideal for my ...

    Transform PDF files into PNG format directly in your web browser

    I am currently utilizing Vue.js and attempting to convert a PDF file to PNG or another image format directly within the browser. My current setup involves reading the PDF from a URL using PDF.js along with the Vue.js component pdfvuer. let instance = this ...

    The iPad screen displays the image in a rotated position while it remains

    Recently, I developed a mini test website that enables users to upload pictures and immediately see them without navigating back to the server. It seemed quite simple at first. $('input').on('change', function () { var file = this. ...

    Incorporating Content-Disposition headers to enable the file to be both downloaded and opened

    I'm having trouble allowing users to both view and download files on a web page. I've tried setting headers and using JavaScript, but can't seem to get it right. My goal is to have an HTML page with two links for each file - one to open in ...

    jQuery-powered unique serial numbers for tables

    I've encountered an issue with my dynamic table that consists of 2 dynamic rows including students, their subjects, and marks. The code in question is provided below: Feel free to check out the code here Snippet for Serial Number function gene ...

    What is the reason for the disparity between CSS box-sizing content-box and border-box?

    Consider the following example where I only changed the CSS box-sizing property from content-box to border-box. The resulting output difference is significant. Give this code a try: .box1 { width: 300px; height: 100px; border: 1px solid blue; pa ...

    Comparing JSON objects with JavaScript models: A guide

    Currently I'm working with angular 2 and I have an array of data. data: MyModel[] = [ { id: 1, name: 'Name', secondName: 'SecondName' } In addition, I have created the interface MyModel: interface MyModel { id: number, nam ...

    remove an element from a nested array using MongoDB

    Greetings everyone! I am currently working on a materials document that contains arrays of articles, each article having an array of details. Here is a snippet from my collection data: { "_id": "62f2404b42556d62e2939466", "code&quo ...

    Unable to retrieve attributes of object in JavaScript

    I attempted various suggestions but none have been successful in allowing me to access the properties of the model. Here is what I have tried so far: var widgetModel = '@Html.Raw(Json.Encode(Model.widgets))'; [].forEach.call(widg ...

    Leveraging the power of express, employing the await keyword, utilizing catch blocks, and utilizing the next

    I am currently developing an express JS application that follows this routing style: router.post('/account/create', async function(req, res, next) { var account = await db.query(`query to check if account exists`).catch(next); if (accoun ...

    Is it not possible to call a function directly from the controller in AngularJS?

    I have been trying to update a clock time displayed in an h1 element. My approach was to update the time by calling a function using setInterval, but I faced difficulties in making the call. Eventually, I discovered that using the apply method provided a s ...