React bootstrap navbar collapse not working

Kane picture Kane · Feb 25, 2019 · Viewed 7k times · Source

I have used react bootstrap navbar also used react-scroll for smooth navigation. It's working fine but navbar is not collapsing when clicking any nav item in the responsive mode.

Packages

import React, { Component } from "react";
import { NavLink } from "react-router-dom";
import { Link } from "react-scroll";
import { LinkContainer } from "react-router-bootstrap";
import { Navbar, Container, NavDropdown, Nav, Dropdown } from "react-bootstrap";

Navbar

<Navbar
    sticky="top"
    id="navbar"
    bg="light"
    expand="lg"
    className="navbar navbar-expand-lg navbar-light bg-light"
    collapseOnSelect={true}
>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
    <Navbar.Collapse id="basic-navbar-nav">
        <Nav className="ml-auto">
            <Link
                activeClass="active"
                to="features"
                spy={true}
                smooth={true}
                offset={-70}
                duration={800}
                className="nav-link"
                onClick={this.closeNavbar}
            >
                Features
            </Link>

            <Link
                activeClass="active"
                to="about"
                spy={true}
                smooth={true}
                offset={-70}
                duration={800}
                className="nav-link"
            >
                About
            </Link>
        </Nav>
    </Navbar.Collapse>
</Navbar>

Answer

Vanya Andreev picture Vanya Andreev · Jun 6, 2019

Had the same issue. I found that "collapseOnSelect" works if we add "eventKey" for Nav.Link item

Example:

import { Link } from 'react-router-dom';
import { Nav, Navbar} from 'react-bootstrap';

 <Navbar collapseOnSelect  expand="lg">
      <Navbar.Toggle />
      <Navbar.Collapse>
        <Nav className="mr-auto d-block">
          <Nav.Item>
            <Nav.Link eventKey="1" as={Link} to="/Home">
              Home
            </Nav.Link>
          </Nav.Item>
          <Nav.Item>
             <Nav.Link eventKey="2" as={Link} to="/Contant">
              Page Contant
            </Nav.Link>
          </Nav.Item>
        </Nav>
      </Navbar.Collapse>
    </Navbar>