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

Alter the td styling depending on the value using AngularJS

I need to dynamically change the style of each td in a column based on its value. There are five different statuses, so each status should have a unique border-color and font-color assigned to it. How can I achieve this using Angular script without hard-co ...

Update your Electron application with the npm update command

I have recently published an app on a local npm repository, and this particular app serves as a crucial dependency for my second electron application. The electron app I am working on is structured around node_modules/my-first-app/dist/index.html. I am w ...

What is the best way to move table data content to a new line?

I have a table that spans the entire width of the screen, with 3 <td> elements inside. The content in the 2nd <td> does not contain any spaces and is quite long, causing it to expand beyond its allotted 70% width and disrupt the layout. Is ther ...

Issue with SMS_MFA not being enabled due to missing delivery configuration in React and AWS Amplify

My React web application, powered by aws-amplify, interacts with AWS Cognito User Pool for user authentication. Users can choose to activate SMS MFA from the app settings. While attempting to enable SMS MFA using the aws amplify npm package, I encountere ...

Collapsing table row in Bootstrap upon button click within the same row

The snippet showcases a basic table with one row containing a button group. Upon clicking the 'main' button (the reset button), the following table row will appear. This behavior is intended only when clicking on the table row itself, not the but ...

Insert a variety of pictures into divs that share the same class

Can I target div elements with the same class in CSS and apply unique styles to each? Here is my HTML: <div class="image"><br/>a</div> <div class="image"><br/>b</div> <div class="image"><br/>c</div> ...

Why is my Angular 2 service not showing up in my application?

Trying to access a JSON file using an Angular service has been unsuccessful. While I can easily read and bind the JSON data without the service, attempting to do so with the service results in an error message: Failed to load resource: the server responde ...

Create a dropdown menu using a PDO query to populate the selectable options

I need to create a Select List that dynamically populates items/information from a Query. I understand the importance of updating the select list every time the database is updated, so JQuery is required for this task. Although I have limited experience wi ...

Modify the Color of Chosen Anchors for Site Categories WITHOUT Using JavaScript

Is there a way to change the color of section anchors in a fixed header when selected without using JavaScript? I'm looking for a CSS-only solution that will change the color of the selected anchor and revert it back to normal when another anchor is c ...

Modifying state within useEffect while also including the redux value as a dependency array

I am facing an issue with my Redux array and the dependency array in my useEffect. The problem arises when I store the value of the Redux array in a variable using useSelector, which is then used as a dependency in my useEffect. The logic inside the useE ...

Images are failing to render on Next.js

Hello there! I am facing an issue while working on my Next.js + TypeScript application. I need to ensure that all the images in the array passed through props are displayed. My initial approach was to pass the path and retrieve the image directly from the ...

Updating an iframe's content URL

I am currently working on building a website using Google Web Design and everything is going well so far. I have added an iFrame to the site and now I am trying to figure out how to change its source when a button is pressed. Most of the information I fo ...

retrieve data from jsp page using ajax request

I've coded this JSP snippet Map<String, Long> map = new HashMap<String, Long>(); map.put("A", 10L); map.put("B", 20L); map.put("C", 30L); JSONObject json = new JSONObject(); json.accumulate ...

A helpful guide on rendering nested maps from JSON data in React.JS

I am attempting to display menu values from a JSON data. This menu has multiple levels, so I am using a nested map function to render the complete menu. const menu = { data:[ { title: "Home", child: [ { title: "SubL ...

Change the order of numbering in ordered lists

I am seeking a way to change the ordering of an ordered list to be in descending order. You can view a live example here. Instead of having the counter span multiple ol elements, I would like the counter to reset after each ol. For the live demo, the des ...

Getting a variable from outside of the observable in Angular - a step-by-step guide

I have an Observable containing an array that I need to extract so I can combine it with another array. this.builderService.getCommercialData() .subscribe( data=>{ this.commercialDetails = data; this.commercialDetailsArr ...

The numbering in the list does not align vertically with the corresponding content

I am attempting to create an ordered list with collapsible sections inside the li elements. The goal is to display basic information about a specific context, and when clicking on a link, additional details are shown. While the code is functional, I am fac ...

I prefer boxes to be aligned next to each other without any gaps, and I won't be

In my quest to showcase 3 boxes seamlessly lined up in a row, I am faced with the challenge of eliminating spaces between them. My goal is to accomplish this feat without resorting to the font-size property. html,body { height:100%; width ...

Adaptable Design for Smartphones

Currently in the process of creating a website for my brother with Joomla 3.4 and Bootstrap. This marks my first venture into building a responsive site, so I'm seeking guidance on essential elements to include in my CSS such as font sizes in specific ...

"By selecting the image, you can initiate the submission of the form

I am trying to figure out why clicking on the image in my form is triggering the form submission by default. Can someone please provide guidance on this issue? <form name="test1" action="er" method="post" onsubmit="return validateForm()" <input ty ...