Closing bootstrap navbar on click of link

Maybe someone has some ideas. I am just about done with the project, used bootstrap and react to complete it. The navbar is bootstrap , I just cant seem to find way to collapse the navbar when a link is clicked. I tried the example

data-bs-target=".navbar-collapse.show

Which closes the navbar but does not go to the link

Using Bootstrap 5
Here is what my nav looks like

import React, {Component, useState} from "react";
import './index.css';
import {NavLink} from "react-router-dom"

class Navigation extends Component{
    constructor(props){
        super(props);
    }
    
    render(){
      
        return(
            <div>
   <nav className="navbar navbar-expand-lg navbar-dark">
  <div className="container-fluid">
    <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">
      <span className="navbar-toggler-icon "></span>
    </button>
    <div className="collapse navbar-collapse" id="navbarTogglerDemo01">
      <NavLink className="navbar-brand" to="/">Planets</NavLink>
      <ul className="navbar-nav ms-auto mb-2 mb-lg-0">
        <li className="nav-item">
          <NavLink className="nav-link" data-bs-toggle="collapse"  aria-current="page" to="/">Home</NavLink>
        </li>
        <li className="nav-item">
          <NavLink className="nav-link" to="/earth">Earth</NavLink>
        </li>
        <li className="nav-item">
          <NavLink className="nav-link" to="/jupiter">Jupiter</NavLink>
        </li>
        <li className="nav-item">
          <NavLink className="nav-link" to="/venus">Venus</NavLink>
        </li>
        <li className="nav-item">
          <NavLink className="nav-link" to="/mars">Mars</NavLink>
        </li>
        <li className="nav-item">
          <NavLink className="nav-link" to="/saturn">Saturn</NavLink>
        </li>
        <li className="nav-item">
          <NavLink className="nav-link" to="/uranus">Uranus</NavLink>
        </li>
        <li className="nav-item">
          <NavLink className="nav-link" to="/neptune">Neptune</NavLink>
        </li>
      </ul>
    </div>
  </div>
</nav>
</div>
        )
    }
}

export default Navigation;

Here is what a typical application looks like

import React, {Component} from "react";
import './index.css';
class Neptune  extends Component{
    constructor(props){
        super(props);
        this.state = {
            content: "Neptune is the eighth and farthest-known Solar planet from the Sun. In the Solar System, it is the fourth-largest planet by diameter, the third-most-massive planet, and the densest giant planet. It is 17 times the mass of Earth, more massive than its near-twin Uranus.",
            source:"https://i.ibb.co/41rw7h1/planet-neptune.png"
        }
    }
    innerButton = (evt) => {
        this.setState({
            content: "Neptune's internal structure resembles that of Uranus. Its atmosphere forms about 5% to 10% of its mass and extends perhaps 10% to 20% of the way towards the core. Increasing concentrations of methane, ammonia and water are found in the lower regions.",
            source:"https://i.ibb.co/0Gvjsyt/planet-neptune-internal.png"
        })
    }
    overviewButton = (evt) => {
        this.setState({
            content: "Neptune's atmosphere is 80% hydrogen and 19% helium. A trace amount of methane is also present. Prominent absorption bands of methane exist at wavelengths above 600 nm, in the red and infrared portion of the spectrum.",
            source:"https://i.ibb.co/41rw7h1/planet-neptune.png"
        })
    }
    geologyButton = (evt) => {
        this.setState({
            content: "The composition of Uranus's atmosphere is different from its bulk, consisting mainly of molecular hydrogen and helium. The helium molar fraction, i.e. the number of helium atoms per molecule of gas, is 0.15±0.03 in the upper troposphere.",
            source:"https://i.ibb.co/TR0C5gz/geology-neptune.png"
        })
    }
    render(){
       
        return(
    <div>
        <div className="img-text-container">
            <div>
                <img src={this.state.source} className="planetImg"/>
            </div>
            
            <div className="planetInfo">
                <div className="planet-heading-info">
               <h1>{this.props.planetName}</h1>
               <p>{this.state.content}</p>
               </div>
                <div className="planet-button">
               <button className="full-text" onClick={this.overviewButton}>01 Overview</button>
               <button className="short-text" onClick={this.overviewButton}>Overview</button>
               <button className="full-text" onClick={this.innerButton}>02 Internal Structure</button>
               <button  className="short-text"onClick={this.innerButton}>structure</button>
               <button className="full-text" onClick={this.geologyButton}>03 Surface Geologist</button>
               <button className="short-text" onClick={this.geologyButton}>Surface</button>
             </div>
            </div>
        </div>
            <div className ="planet-stats">
                <div className="rotation planet-stats-style"> 
                 <p>Rotation Time:</p><p>{this.props.rotation}</p>
                </div>
                <div className="revolution planet-stats-style">
                 <p>Revolution Time:</p><p>{this.props.revolution}</p>
                </div>
                <div className="radius planet-stats-style">
                 <p>Radius:</p><p>{this.props.radius}</p>
                </div>
                <div className="temp planet-stats-style">
                 <p>Avg Temp:</p><p>{this.props.temperature}</p>
                </div>
            </div>
    </div>
        )
    }
}
export default Neptune;

I have been pouring over the internet for hours, and have not found a solution yet

Not sure what the best way of doing it is. You need to add the collapsed class to the button and remove the show class from the links container.

Here it is with just some classList code and the Bootstrap JS for the button logic.

Here it is with state and conditional classes without the Bootstrap JS for the button logic. So you handle the class toggling.

These are made with hooks correct? I have not got there yet in the lessons. While I was searching all over the internet I found an example about perhaps using history to redirect the route. Originally, I made a function that closed the navbar on a onclick and again it didnt follow the route. So, I tried using history but the error came back saying it has to be used in a functional component. As far as I know, hooks let use state and other features without having to use a class

Yes, the hooks are used with functional components.

For the first sandbox code instead of useRef you would use createRef and the handler function would be a method. For the second, you would use the state object and setState instead of the useState hook and the handler would be a method.

The nav really should not close (on its own) if you navigate to a different route as long as you have placed it correctly. That is the expected behavior. It should be outside the routes and individual components. So it would remain in the same open state when navigating to a new route.

As an aside, I would suggest learning React using other resources than just fCC. There is nothing wrong with knowing about classes but it is an outdated way of writing React.

Im actually following a course on Udemy. Same instructor I have been using for everything, but I did notice it was outdated. At least the beginning of it. The way the instructor showed how to do react router was a couple updates behind. So, I had to look it up to get it the way is is now.

I saw a post saying it was outdated, but someone else made a good point. They mentioned along the lines if one day I was working on a project from a company that was still using classes, that it would still be good to know how to work with them. Im hoping to get to hooks sometime this week.

As I said there is nothing wrong with knowing about classes and you would obviously have to write some React code using classes to really learn how to use classes.

I would however not put too much focus on them when first starting. That is just backward. Learning classes will not make it easier to learn hooks with functional components, on the contrary, most devs that learned classes initially had a bit of a hard time switching to hooks.

I would learn modern React and then if you do need to learn classes (for work or just working with old code) do that.

Good to know. I will move on to them then.

It’s just cleaner code and in my opinion, more enjoyable code to write. For one, you do not need to write this all the frickin time. That is still the one thing that annoys me the most when suddenly having to write class-based React. It is just so verbose compared to hooks and functions.

It definitely has some gotchas, but after you have gotten used to it I think you will like it.

Thats good to know. I was glad that the use of arrow functions got rid of binding. That got old pretty quick having to write stuff like this every time

 this.handleClick = this.handleClick.bind(this);

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.