Highlight react-bootstrap NavItems with a underline on scroll in React

I am currently working on a website where I have implemented a react-bootstrap navbar with several Nav items. My goal is to enable smooth scrolling through the page, where each section corresponds to an underlined NavItem in the navbar or when clicked, automatically scrolls to that specific section. I attempted to find a solution online and came across react-scroll, but I'm unsure how to integrate it with my existing react-bootstrap code.

Below is my Navbar Component:

export const NavbarComponent = () => {
    return (
      <>
      <Navbar collapseOnSelect className="style-navbar">
        <Container>
          <Navbar.Brand className="style-navbrand" href="/">
              <div class="inl">LOGO</div>
              <div className="style-subheading">Subheading</div>
          </Navbar.Brand>
          <Nav className="style-nav">
          <Nav.Item className="style-navitem">
            <Nav.Link className="style-navlink" href="/home">ABOUT</Nav.Link>
           </Nav.Item>
           <Nav.Item className="style-navitem">
            <Nav.Link className="style-navlink" href="/members">MEMBERS</Nav.Link>
            </Nav.Item>
            <Nav.Item className="style-navitem">
            <Nav.Link className="style-navlink" href="/pricing">Pricing</Nav.Link>
            </Nav.Item>
          </Nav>
          <Nav>
              <Nav.Link id="style-navlink" href="/contact">CONTACT</Nav.Link>
          </Nav>
        </Container>
      </Navbar>
      </>

Here's a glimpse into my App.js file:

  return (
    <div className="style-background">
      <div className = "style-backg-sheet">
        <NavbarComponent/>
        <AboutComponent/>
        <MemberComponent/>
        <PricingComponent/>
      </div>
    </div>
  );
}

AboutComponent snippet:

import React from 'react'
import {Container} from 'react-bootstrap';

const About = () => {
    return (
        <div>
            <Container>
                <h1>About</h1>
                <p>Some text</p>
            </Container>
        </div>
    )
}

export default About

In essence, I aim to create distinct sections on a single webpage where clicking on a specific navbar item will highlight it and smoothly scroll down to the corresponding section (e.g., clicking on Pricing would lead to the pricing section displaying text and images).

Answer №1

If your goal is to ensure that the links navigate to specific sections and highlight the active menu item, here are some suggestions:

  • Assign a unique id attribute to each section you want to link to.

    const About = () => {
      return (
        <div className="section" id="about">
          <Container>
            <h1>About</h1>
            <p>Some text</p>
          </Container>
        </div>
      );
    };
    
  • Include hashlinks in the navigation items

    <Nav.Link className="style-navlink" href="#about">
      About
    </Nav.Link>
    
  • Add CSS styles to highlight the active menu item link

    a.style-navlink.active {
      color: #000;
      font-weight: bold;
      text-decoration: underline;
    }
    

https://i.stack.imgur.com/X0llb.png

https://codesandbox.io/s/determined-mendel-qzit33?fontsize=14&hidenavigation=1&module=%2Fsrc%2FApp.js&theme=dark

To ensure smooth scrolling to sections, consider using third-party libraries like react-router-hash-link. This allows for better control over scrolling behavior when making the navbar sticky or fixed at the top of the page.

import { NavHashLink } from "react-router-hash-link";

...

<Nav.Link
  activeClassName="active-link"
  as={NavHashLink}
  className="style-navlink"
  smooth
  to="#about"
>
  About
</Nav.Link>

...
.active-link {
  color: #000;
  font-weight: bold;
  text-decoration: underline;
}

https://i.stack.imgur.com/yWsNh.png

https://codesandbox.io/s/react-underline-react-bootstrap-navitem-when-scrolling-down-react-router-hash-link-og6tnz?fontsize=14&hidenavigation=1&module=%2Fsrc%2FApp.js&theme=dark

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

Is there a substitute for AngularJS $watch in Aurelia?

I'm in the process of transitioning my existing Angular.js project to Aurelia.js. Here is an example of what I am trying to accomplish: report.js export class Report { list = []; //TODO listChanged(newList, oldList){ ...

Guide on setting a wait while downloading a PDF file with protractor

As I begin the download of a pdf file, I realize that it will take more than 2 minutes to complete. In order to verify if the file has successfully downloaded or not, I will need to wait for the full 2 minutes before performing any verification checks. C ...

What could be the reason why I am unable to load the ejs file?

https://i.stack.imgur.com/91bPg.png Issue: Unable to find the "index.ejs" view in the views directory ...

achieving initial value to show upon page load

I'm trying to set a default value that is visible when the page loads. My goal is to have the first button always displayed by default in the "display-donation" div whenever someone visits the form. Currently, when the page loads, 10 is highlighted ...

Tips for transferring simple CSS formatting to an independent stylesheet

As part of a university project, I am working on a basic website. Initially, I used in-line styling for the website design. However, the subject coordinator has now changed the requirements and we are only allowed to use an external CSS stylesheet. Most of ...

Detecting the scroll events of elements with the overflow:hidden property

Looking to synchronize scrolling between two different panels or divs? In one element, there's an overflow: auto while the other has overflow: hidden (trying to mimic a grid with frozen columns). I've managed to sync the scroll when it occurs w ...

Exploring the capabilities of NEXTJS for retrieving data from the server

When trying to retrieve data from the nextjs server on the front end, there is an issue with the code following the fetch() function inside the onSubmit() function. Check out the /test page for more details. pages/test const onSubmit = (data) => { ...

Error in Node.js: "No callback function provided, it is undefined."

Currently diving into the realm of React through a course that involves building a video rental application. The instructor has provided the backend code, and our task is to establish the connection between the frontend and backend. When attempting to subm ...

Increase the date and time by a specified number of days

After searching for solutions on how to add a specific number of days to a given date, I came across various methods. However, my requirement is to add days to both Date and Time in the format MM-DD-YYYY HH:MM:SS. I attempted a method which worked fine wh ...

Circular CSS menu

What I'm Trying to Achieve: I am interested in developing a unique radial menu that includes interactive elements, such as the central image and the surrounding sections. It is imperative that the solution is compatible across all browsers. The examp ...

Update the nested radio button to a new value

I have a series of radio button lists generated using ng-repeat. I've managed to capture the selected item successfully. Now, I am attempting to set the default value for the radio buttons. Could someone please provide assistance? Below is my code sni ...

Implementing React.JS to dynamically update a value from a websocket and store it within

I want to create a dynamic stock price table that updates with live stock prices using websockets. I have all the necessary data and need to update my stock price object with the live price. How can I access the variable and insert the value into the obj ...

We received an error message saying: "The module could not be found: Unable to resolve '/root/project/node_modules/eslint-loader/index.js' in the

I am currently working on my first React project using the material-ui-kit from Creative Tim. I encountered an issue when trying to import a component and need some assistance. Here is my file structure: project | +--src | +--components | | | ...

IE Script loading

There is a script that I have, it appends in the document like so: window.d = document s = d.createElement('script') s.setAttribute('type','text/javascript') s.setAttribute('src',options.url) d.getElementById ...

Activate a particular panel within the leftPanel using PDFNet Webviewer

When using disableElements in the setQuickBarPanelContents() function, I am able to remove 2 of the 3 panels from the leftPanel: setQuickBarPanelContents() { this.instance.disableElements(['notesPanel', 'notesPanelButton', &apos ...

Dynamic Select Box with Display of 2 Buttons

Looking to create an Ajax combo box with options for Female and Male. I would like to display a button for Female and a button for Male. Here is the code that I have: <!DOCTYPE html> <html> <head> <style> #for-male, #for-female{ ...

Angular: facing difficulty displaying static html pages on server, although they render correctly when run locally

Within my Angular project, I have stored a few static html files (specifically sampleText.html) in the src/assets/html folder. In one of my components, I am attempting to fetch and display this file. The following code is being used for this purpose. Every ...

Guide to ensuring the navbar remains at the top of the webpage following an image

I am attempting to create a sticky navbar that stays at the top of the page once the header has been scrolled past. It should have a similar effect as shown in this example on codepen.io, but with the addition of an image that stretches across most of the ...

Tips for showcasing the information from a JSON document in React

I have a JSON file stored statically in my public directory and I'd like to show its content within a React component (specifically NextJS). The goal is to simply render the JSON as it is on the page. import data from '../../public/static/somedat ...

React-select-pagination is failing to retrieve data while scrolling

Struggling to load over 20,000 options using react-select from a Node API database? The page was barely loading until I implemented "react-select-async-pagination". However, there's a problem - the data is only fetched once. import React, { useRef, us ...