Guide on implementing a navbar in a React Application to navigate to a specific page and automatically scroll to a particular element

(UPDATED)
I am working on a react app where I need to include the navbar on each page. To achieve this, I created a navbar component and added it to all new pages. The navbar functions correctly on the main page by scrolling to the selected section. However, on other pages, the navbar is unable to scroll to the section because it cannot find it. My query is how can I make the navbar clickable to redirect to the main page and then scroll to an element.

Below is the simplified code

Navbar Component Code

export default function Navbar(){
    return(
        <div className="nav-container">
        <nav>
            <ul className="desktop-nav">
                <li>
                    <a
                        className="link-logo" 
                        onClick = {() => {scrollTo('landing-page')}}
                    />
                </li>
                <li>
                    <a onClick = {() => {scrollTo('elem1')}}>elem1</a>
                </li>
                <li>
                    <a onClick = {() => {scrollTo('elem2')}}>elem2</a>
                </li>
                <li>
                    <a onClick = {() => {scrollTo('elem3')}}>elem3</a>
                </li>
            </ul>
        </nav>
        </div>
    );
}
function scrollTo(elem){
    document.getElementById(elem).scrollIntoView(true);
}

Main Page Component Code

export default function Home(){
    return(
        <div>
            <div id = 'elem1'>elem1</div>
            <div id = 'elem2'>elem2</div>
            <div id = 'elem3'>elem3</div>
            <a href = '/somewhere'> Go to Second Page </a>
        </div>
    );
}

App Router Code


function App() {
    return (
        <Router>
            <Switch>
                <Route exact path='/' component={SITE} />
                <Route exact path='/somewhere' component={SECOND_PAGE}/>
            </Switch>
        </Router>
    );
}

export default App;

From the SECOND_PAGE component displayed as a separate page, how can I ensure that the navbar links redirect to the SITE component and scroll to the specified link without altering the URL? I aim to keep the URL static while navigating between these two components and prevent users from viewing my div IDs and class names if possible.

Answer №1

If you want to enable linking and navigating to specific sections on a page while scrolling into view, I recommend integrating react-router-hash-link into your project.

Here is an example using the provided code snippet:

import { Link, Switch, Route } from "react-router-dom";
import { HashLink } from "react-router-hash-link";

const NavBar = () => (
  <div className="nav-container">
    <nav>
      <ul className="desktop-nav">
        <li>
          <HashLink smooth to="/#">
            Home
          </HashLink>
        </li>
        <li>
          <HashLink smooth to="/#elem1">
            elem1
          </HashLink>
        </li>
        <li>
          <HashLink smooth to="/#elem2">
            elem2
          </HashLink>
        </li>
        <li>
          <HashLink smooth to="/#elem3">
            elem3
          </HashLink>
        </li>
      </ul>
    </nav>
  </div>
);

const Home = () => {
  return (
    <div>
      <div className="section" id="elem1">
        elem1
      </div>
      <div className="section" id="elem2">
        elem2
      </div>
      <div className="section" id="elem3">
        elem3
      </div>
      <Link to="/somewhere"> Go to Second Page </Link>
    </div>
  );
};

const SecondPage = () => <h1>Second Page</h1>;

export default function App() {
  return (
    <div className="App">
      <NavBar />
      <Switch>
        <Route path="/somewhere" component={SecondPage} />
        <Route path="/" component={Home} />
      </Switch>
    </div>
  );
}

https://codesandbox.io/s/elastic-joliot-fr387?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

Tips for successfully sending a nested function to an HTML button and dropdown menu

I'm working on two main functions - getChart() and fetchData(). The goal is to retrieve chart data and x/y axes information from a database. Within the getChart function, I'd like to incorporate a dropdown menu for displaying different types of c ...

Effortlessly update value changes in ReactJs when Checkbox is checked

I've been stuck on this issue for a whole day now. I'm trying to make it so when the checkbox is checked, the value of 'Done' changes as intended. I've tried using useState but it's not working. The approach I used below is mu ...

Troubleshooting issue with JQuery AJAX loading Bootstrap Dropdowns

I have a website on GitHub Pages that uses Bootstrap, but I'm having issues with the drop-down menu in the navbar. Sometimes it works and sometimes it doesn't. I am using $("#nav").load("url"); to load the navbar so that I can make changes and ha ...

Unusual behavior: Jest throws a `Cannot find module` error when attempting to import components using absolute paths

Configuration of my jest: clearMocks: true, rootDir: '../../', cacheDirectory: 'cache', testEnvironment: 'jsdom', modulePaths: [ '<rootDir>' ], setupFilesAfterEnv: [ '<rootDir>/ ...

When executing the app.delete function, the req.body is found to be empty

I've encountered an issue when trying to send JSON data in an $http Delete call, as the req.body returned is coming back as an empty JavaScript object. Below is my $http delete call where "scenario" is a json object: //Deletes the item from the data ...

The jQuery div enclosure technique

I am trying to wrap HTML around an existing div, here is what I have attempted: HTML: <input type="text" data-placeholder="username" /> It should look like this when rendered: <div class="placeholding-input"> <input type="text" data-pl ...

submission thwarted by preventDefalut()

Having some difficulties with my ajax login validation using javascript. I am facing an issue with e.preventeDefault() as it prevents the submission and always displays a validation error for empty fields. Removing it allows the form to be submitted, but t ...

Three.js: Buffer geometry does not provide any performance improvement

After examining the Three.js example found at webgl_performance, I decided to try improving performance by converting the model into a buffer geometry using the following code: var buffer = THREE.BufferGeometryUtils.fromGeometry( geometry ); Despite my e ...

Running Page Load Twice Occurs When HREF Attribute is Set to "#" in Link Tag

I've encountered an odd issue that I could use some help with. When I include a link tag with the "href" attribute set to "#", it seems to trigger the Page Load event twice. For instance, in the example below, I have used "#" as the value for the "hr ...

Optimizing the performance of J2EE web applications

I am currently working on enhancing the performance of my web application. The application is java-based and is hosted on an Amazon cloud server with JBoss and Apache. One particular page in the application is experiencing a slow loading time of 13-14 sec ...

Working with promises and Async/Await in Express/node can sometimes feel ineffective

Currently, I am delving into the world of node and express with the aim to create a function that can extract data from a CSV file uploaded by the user. My challenge lies in the fact that the data is being outputted as an empty array before it goes through ...

Complete the table until it reaches the available space, making sure to maintain the header and footer

In my live page, I have a section that has limited space based on the viewport size. The layout includes: Content above the table Table with Header and Body Content below the table Currently, the section overflows due to having too many items in the tab ...

Modify the current URL to the AJAX GET request URL using jQuery

I am currently developing filters for my website. Users have the ability to select multiple filters simultaneously, with results being updated accordingly, akin to most E-commerce platforms. I have successfully implemented a function that utilizes an ajax ...

Button outline appears upon clicking the link and remains until another area of the page

I have always been curious about a particular situation: Imagine you have a one-page website with a navigation menu. When a user clicks on a navigation link, it scrolls to that section of the website. However, after clicking, the navigation link remains v ...

Tips and tricks for ensuring images maintain their aspect ratio and height when resizing for responsiveness

I am facing an issue with my two-column layout. One column contains an image and the other column has text and buttons with a fixed height. To ensure the image is responsive, I have set the width to 100% and height to auto. However, upon resizing, the aspe ...

The checkbox in angular js is failing to be marked as selected

<tr ng-repeat="languages in samln"> <td> <span>{{languages.emplang}}</span> </td> <td> <input type="checkbox" name="checkbox1-" id="sp1" value="false" style="margin-left:40px;" ng-model="languages ...

I am facing an issue where the state in Next.js React does not get updated when passing a

"use client"; import { EntityType, World } from "@/types/World"; import React, { useState } from "react"; import dynamic from "next/dynamic"; ; let RayTracingPage = dynamic(()=>import("./RayTracingCanvas&qu ...

Is there a way to code an automatic way to trigger the opening of a Material-UI Select field?

If you're looking for the select field, check it out in the Material-UI demo here Although its methods seem to be inherited from the menu/popover classes, I've been struggling to trigger the 'open' action when the onFocus event occurs. ...

Discover the elements that are currently utilizing jQuery widgets

I currently utilize the jQuery-File-Upload plugin in my project, but I believe my query can apply to any jQuery plugin. The API documentation suggests initiating the plugin using the fileupload method, like so: $('#fileupload').fileupload(); My ...

sending an array from one CodeIgniter view to another view via Ajax

In the following code segments of my application, myArray is an array where each element contains a few objects that I need to use in a second view. When I use alert(myJSON);, I am able to see the array in the alert window. However, when the view loads, i ...