The useRouter hook from next/router was unable to connect because NextRouter was not activated

import { useRouter } from 'next/router';
const Navbar2 = () => {
  const router = useRouter();
 return (
    <nav className={`fixed top-0 w-full px-10 bg-white p-4 transition-all duration-500  ${isVisible ? 'top-0' : 'top-[-160px]'}`}>
      <div className="flex items-center justify-between">
        {/* Brand Logo  */}
        <div className="w-[40%]">
          <Image src={logo} alt="Brand Logo" className="w-20" />
        </div>
        {/* menu item */}
        <div className="flex-1">
          {/* main menu */}
          <ul className="flex items-center justify-between mt-10">
            <li><Link href="/" className={router.pathname === '/' ? "text-[#7B003B]" : ''}>Home</Link></li>
            <li><Link href="/" className={router.pathname === '/' ? "text-[#7B003B]" : ''}>About us</Link></li>
            <li><Link href="/" className={router.pathname === '/' ? "text-[#7B003B]" : ''}>Admission</Link></li>
            <li><Link href="/" className={router.pathname === '/' ? "text-[#7B003B]" : ''}>Safeguarding</Link></li>
            <li><Link href="/" className={router.pathname === '/' ? "text-[#7B003B]" : ''}>School life</Link></li>
            <li><Link href="/" className={router.pathname === '/' ? "text-[#7B003B]" : ''}>Sixth Form</Link></li>
            <li><Link href="/" className={router.pathname === '/' ? "text-[#7B003B]" : ''}>News</Link></li>
            <li><Link href="/" className={router.pathname === '/' ? "text-[#7B003B]" : ''}>Alumni</Link></li>
            <li><Link href="/" className={router.pathname === '/' ? "text-[#7B003B]" : ''}>Contact us</Link></li>
          </ul>
        </div>
      </div>
    </nav>
  );
};
export default Navbar2;

This code snippet is designed to display the active nav link, but I encountered an error when attempting to use:

import { useRouter } from 'next/router';

The error I received was: Unhandled Runtime Error

Error: NextRouter was not mounted. https://nextjs.org/docs/messages/next-router-not-mounted

I expected this code to highlight the active link in my navigation menu.

Answer №1

If you're working with the latest versions of NextJS like 13 or 14, remember that useRouter has been moved from next/router to next/navigation.

Furthermore, keep in mind that the pathname attribute is no longer available directly on the router object. Instead, utilize the usePathname hook for this purpose.

Consider organizing your links into an array and using mapping to enhance code readability and reduce redundancy.

Take a look at the code snippet provided below:

import {
  useRouter,
  usePathname
} from "next/navigation";


export default function YourComponent() {
  const router = useRouter();
  const pathname = usePathname();

  return ( < div > Whatever... < /div>)
  }

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

Images showing Strava heat maps retrieved through API

Check out this amazing heatmap created by Strava! I'm curious about how they were able to achieve this - it seems like they are using the API to request overlay images based on the network tab. I have my own geo data, but I'm wondering how I can ...

AngularJS deferred rendering (not deferred loading views)

Imagine having over 3000 items to display within a fixed-height div using an ng-repeat and setting overflow: auto. This would result in only a portion of the items being visible with the rest accessible via scrollbar. It's anticipated that simply run ...

It is not possible to adjust the audio volume using the useRef hook

I keep encountering an error that says The left-hand side of an assignment expression may not be an optional property access whenever I try to adjust the volume of the htmlaudioelement Does anyone have any suggestions on how to resolve this issue? Here i ...

Tips for choosing a loaded element using the jQuery load() method

I am currently facing a challenge with the following (here is a snippet of code to illustrate): <div id="container"></div> <script type="text/javascript"> $('#container').load('content.html'); $('.eleme ...

html scroll to the flickering page

Why is it that when a user clicks on a link in the list, the browser flickers? This issue becomes especially noticeable if a user clicks on the same 'link' twice. Is there a solution to prevent this from occurring? The problem also seems to aris ...

Converting JSON data from an XML document using PHP

While I have a decent understanding of xml and json parsing, I'm facing an issue with this particular site. Here is what I have tried: $json_string="http://meteo.arso.gov.si/uploads/probase/www/plus/timeline/timeline_radar_si_short.xml"; $json = fil ...

Auto Start Feature for jQuery Slider Function

Hey there, I currently have an image slider on my website that allows users to navigate through images by clicking on preview and next buttons. My query is: would it be possible to implement an auto start feature instead of having to click manually? Belo ...

Command for Sniping with Discord.js

I am currently working on creating a snipe command using Discord.js in my bot. I have set up command handlers and everything seems to be working fine, including the on messageDelete event. However, I encounter an error when I delete a user message and try ...

Click on a div in AngularJS to be directed to a specific URL

I'm currently working on developing an Angular mobile app and I want to be able to navigate to a specific URL, like www.google.com, when a particular div is clicked. Unfortunately, I'm still new to the world of Angular and struggling to achieve t ...

Unexpected token N error was thrown while using the Jquery .ajax() function

While working on a form submission feature using JQuery .ajax() to save data into a MySQL database, I encountered an error message that says "SyntaxError: Unexpected token N". Can someone please explain what this means and provide guidance on how to fix it ...

Using ajax to send an array to PHP

I have an array named "heart" that is being sent via ajax... var heart = [31,32,33,34,35,36,37,38,39,42,43]; // Sending this data via ajax to php file/ $.ajax({ type: "POST", data:{ 'system': heart }, url: "login-function.php", success: f ...

ZeroMQ and Electron integration: Unable to find the specified bindings file

Currently, I am running Windows 7 x64 with nodejs 5.1.0 and Electron 0.35. I carefully followed the instructions provided by the Electron Quick Start app and then proceeded to add the line require("zmq") to the main.js file. However, upon executing npm ins ...

Ajax request experiencing 500 Internal Server Error. Uncertain about the source of the issue

I'm encountering a 500 Internal Server Error and I'm struggling to pinpoint the root cause of the issue. The purpose of this request is to delete a comment with a specific id from the database. The id is passed through a hidden input field. Below ...

Setting up StrongLoop LoopBack MongoDB datasource for successful deployment on Heroku

Currently, I am utilizing LoopBack version 1.6 and have a local mongoDB server operational for development purposes with the following datasource configuration: "mongodb": { "defaultForType": "mongodb", "connector": "loopback-connector-mongodb", ...

Implementing user profile picture display in express.js: A step-by-step guide

I'm having trouble displaying the profile picture uploaded by users or employees in my application. Although the picture uploads successfully, it doesn't show up and gives an error when I try to redirect to the page. Cannot read property &ap ...

Dynamic Data Visualization using ChartJS with MySQL and PHP

I'm trying to create a line chart using chartJs that will display MySQL data. Specifically, I would like to use PHP to push the MySQL data to the chartJs. Here is an example of the MySQL table: id | page_views | visitors | month | ---------------- ...

Exploring the Potential of Using ngIf-else Expressions in Angular 2

Here is a code snippet that I wrote: <tr *ngFor="let sample of data; let i = index" [attr.data-index]="i"> <ng-container *ngIf="sample.configuration_type == 1; then thenBlock; else elseBlock"></ng-container> <ng-template #t ...

Enhance your HTML rendering with Vue.js directives

Check out this cool code example I created. It's a simple tabs system built using Vue.js. Every tab pulls its content from an array like this: var tabs = [ { title: "Pictures", content: "Pictures content" }, { title: "Music", c ...

collection of assurances and the Promise.all() method

Currently, I am dealing with an array of Promises that looks like this: let promisesArray = [ service1.load('blabla'), service2.load(), // throws an error ]; My goal is to execute all these Promises and handle any errors that occur, as ...

Acquiring XML data directly in jQuery without any preprocessing

Hey there, I'm dealing with an unusual situation. I need to extract data from an API that returns malformed XML. Each <episode> in the response has its own <title> tag. However, when using $.get or $.ajax, all these titles end up in the &l ...