Managing the Navigation Bar

I am currently using Bootstrap and ReactJS, and I am facing an issue where the active tab on the navigation bar does not change when I scroll down the page. At the moment, the active tab only changes when I click on a specific section. Each section corresponds to a different component on the website. https://i.sstatic.net/WEcmm.png

As shown in the image above, I clicked on the "Recent Projects" tab, which made it active and scrolled down to the recent projects section. However, I want the active tab to change even when I scroll down using the scroll bar.

Here is the code for the navigation bar. Any assistance would be greatly appreciated!

import React from 'react';
import { Link } from 'react-router-dom';
// import Scrollspy from 'react-scrollspy';
import { animateScroll as scroll, scroller} from 'react-scroll';
import './Navigation.css';

export default function MainNavigation() {
  let didScroll = false;

  window.onscroll = () => didScroll = true;

  setInterval(() => {
      if ( didScroll ) {
          didScroll = false;
          console.log('Someone scrolled me!')
      }
  }, 250);

  const scrollFunc=(e)=>{
    if(e==='home'){
      scroll.scrollToTop()
      for(var j = 2; j<=4; j++)
      {
        var navbarSpy = "navMain-" + j;
        document.getElementById(navbarSpy).className = "nav-item";
      }
      document.getElementById("navMain-1").className = "navbar-brand";
    }
    else {
      scroller.scrollTo(e, {
        duration: 1400,
        delay: 0,
        offset: 25,
        smooth: 'easeInOutQuart'
      })
      for(j = 2; j<=4; j++) {
        navbarSpy = "navMain-" + j;
        document.getElementById(navbarSpy).className = "nav-item";
      }
      var tab = 2;
      if (e==='recentProjects')
        tab =3;
      if(e==='contact')
        tab=4;
      navbarSpy="navMain-" + tab;
      document.getElementById(navbarSpy).className = "nav-item active";
    }
  }
  return (
    <div>
      <nav className="navbar fixed-top navbar-expand-lg navbar-dark bg-dark" id="mainNavbar">
        <a className="navbar-brand" id="navMain-1" style={{cursor:"pointer"}} data-toggle="collapse" data-target=".navbar-collapse.show" onClick={() => scrollFunc("home")}>
          <img src={require('./logo_transparent.jpg')} width="30" height="30" className="d-inline-block align-top" alt=""/>
          Home
        </a>
        <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false" aria-label="Toggle navigation">
          <span className="navbar-toggler-icon"></span>
        </button>

        <div className="collapse navbar-collapse" id="main-navbar">
          <ul className="navbar-nav mr-auto">
             
            <li className="nav-item" id="navMain-2">
              <a className="nav-link" onClick={() => scrollFunc("aboutme")} data-toggle="collapse" data-target=".navbar-collapse.show" style={{cursor:"pointer"}}>About Me</a>
            </li>
            <li className="nav-item" id="navMain-3">
              <a className="nav-link" onClick={() => scrollFunc("recentProjects")} data-toggle="collapse" data-target=".navbar-collapse.show" style={{cursor:"pointer"}}>Recent Projects</a>
            </li>
            <li className="nav-item" id="navMain-4">
              <a className="nav-link" onClick={() => scrollFunc("contact")} data-toggle="collapse" data-target=".navbar-collapse.show" style={{cursor:"pointer"}}>Contact Me</a>
            </li>
          </ul>
        </div>      
      </nav>
    </div>
  );
}

Answer №1

Avoid using the setInterval function, as an onScroll event listener will be triggered each time a user scrolls. To achieve this, place the event listener within a hook that will execute only once.

React.useEffect( () => { // This will only be executed on initial render
  window.addEventListener('scroll', () => { // This adds a single event listener
    console.log(window.scrollTop); // Displays the distance scrolled from the top
    // Implement your logic here to highlight the appropriate navigation item based on window.scrollTop
  }
}, [] )

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

Encountering issues while attempting to utilize pdf2json in a TypeScript environment

When attempting to import pdf2json (3.0.1) into my Node project using TypeScript, I encountered the following error: "Could not find a declaration file for module 'pdf2json'." I also tried installing @types/pdf2json for TypeScript but found tha ...

What could be the reason behind getting a useLayoutEffect error when using renderToString to render a Material-UI component?

Currently, I am utilizing React version 16.12.0 along with @MaterialUI/core version 4.8.1. The challenge I am facing involves creating a custom icon for a React Leaflet Marker. The icon in question is a Fab component sourced from Material-UI. In order to ...

ERROR: Unexpected issue occurred with v8::Object::SetInternalField() resulting in an internal field going out of bounds while utilizing node-cache in Node.js

I recently started working with API exports that contain a large amount of data, so I decided to utilize the node-cache in order to speed up the API response time, as it was taking more than 2 minutes to retrieve the data. Being new to this, I came across ...

Examining REST API functionality through the use of a Console, requiring an integer list as a parameter

Currently, I am in the process of testing a REST API to perform an action that requires a list of integers. I am uncertain about how to correctly handle the parameters required for this test. In my request payload, I have included the following: idAttac ...

Tips for accessing the @keyframes selector and extracting the value from it

In my CSS code, I have a shape element with an animation that spins infinitely for 50 seconds. #shape { -webkit-animation: spin 50s infinite linear; } @-webkit-keyframes spin { 0% { transform: rotateY(0); } 100% { transform: rotateY(-360deg ...

Submit function causes mutation in React form state

My current project involves learning React on my own and creating a small single-page React app using an Axios API. I'm facing a persistent issue with a POST request that keeps failing. After extensively using console.log, it appears that the form inp ...

Anyone have a sample showcasing the integration of VueJS with the latest webpack 4 configuration?

VueJs templates now come with numerous examples and starting project skeletons. However, most of them still utilize webpack v3. Has anyone experimented with webpack 4? I'd love to see how you integrate version 4 of webpack into a VueJs project. Thank ...

Searching for an element using Python's Selenium and JavaScript

on this page I am trying to click on the "Choose file" button but I keep getting the error message: javascript error: argument is not defined var1 = sys.argv[1] path = os.path.abspath(var1) driver.get("https://www.virustotal.com/gui/home/upload& ...

Currently seeking user coordinates for Vue implementation

I recently started using Vue and I'm working on capturing the lat/long of a user to be used in other functions within Vue. Currently, I am retrieving the coordinates and plan to utilize them in an API but for now, I am just logging them. Although I c ...

Conceal an item if the span element encompasses a div with a specific class

I am struggling with a problem where I need to hide an "i" element only if a "span" contains a "div" element. The content inside the "span" is loaded via AJAX and rendered as HTML, so it may contain the "div class=difference" or not. The code snippet in q ...

jQuery Triggered Download Resulting in 'Error: Connection Issue'

I need to trigger a download using a JQuery AJAX request once it's finished. EXAMPLE CODE: $('.getPDF').click(function(){ var filepath = 'localhost:3000/pdf/formula-' + this.id + '.pdf'; $.ajax({ url: '/formu ...

Place a locator on the variable at the identical level

My objective is to locate an element with both an id and a class. I achieve this using the following code snippet: return element(by.css('#right.closed')).isPresent(); While this method works correctly, I am looking to enhance it by introducing ...

The method defined in user.model.js cannot be utilized in mongoose and node

When developing an app with node and mongoose, I encountered a peculiar issue while testing. Below is my auth.index.js file for user login. auth.index.js: var express = require('express'); var mongoose = require('mongoose'); var passp ...

The process involves transferring information from a specific div element to a database. This particular div element obtains its data after receiving an appended ID

It's a bit complicated, but I'm working on creating a tag system. I'm fetching data from a database with an AJAX call using the "@" symbol. Everything is working fine - the tags are being generated, but I'm having trouble retrieving and ...

Is it possible for CSS to prevent the insertion of spaces?

When filling out a form, I am able to insert spaces in inputs but not in the textarea (which is necessary). Interestingly, inserting spaces in the textarea works flawlessly. <form action="/#wpcf7-f519-o1" method="post" class="wpcf7-form" enctype="mu ...

Navigation isn't aligning correctly on the right side

I am having trouble with my navigation menu not aligning properly to the right. <div class="logo"> <h2><i class="icon-reorder"></i> Frosty</h2> </div> <div class="nav"> <a href="#">Home</a> </div& ...

What could be causing the "undefined property read" error even though the data is clearly defined?

export async function getPrices() { const res = await fetch( "https://sandbox.iexapis.com/stable/crypto/BTCUSD/price?token=Tpk_1d3fd3aee0b64736880534d05a084290" ); const quote = await res.json(); return { props: { quote } }; } export de ...

Testing a React component that uses useParams: A step-by-step guide

I've been working on creating a BBS App using TypeScript, React, React Router, and React Testing Library. However, I've encountered an issue where a component utilizing useParams is not passing a test. Interestingly, it seems to be working correc ...

The background-size:cover property fails to function properly on iPhone models 4 and 5

I have taken on the task of educating my younger sister about programming, and we collaborated on creating this project together. Nicki Minaj Website However, we encountered an issue where the background image does not fully cover the screen when using b ...

Unable to Trigger Jquery Scroll Event

I'm trying to figure out why a div is not appearing when the page is scrolled down. The issue is that my page body and most other elements have overflow hidden, except for a table that appears at a certain point on the page when a button is pressed. T ...