Ways to retrieve the currently selected id from the router within the next 14 steps

I'm currently trying to extract the ID that is selected (#about, #home, #blog) or the full path (http://localhost:3000/#about, http://localhost:3000/#home) from the router. I am working with Next.js version 14.0.3

This is my approach: My current URL is http://localhost:3000/#about

"use client";

import { useEffect, useState } from "react";
import {useParams, usePathname} from "next/navigation";

function NavBar() {
  const [activeItem, setActiveItem] = useState("#about");
 
  const params = useParams();
  console.log(params); //output: {}

  const path = usePathname();
  console.log(path); // output: /

  return <SomeComponent/>
}

trying to add styling to the active navigation item based on the selected id

Answer №1

Grab the useRouter function from next/router library and get the URL of the current page by following this example :

import { useRouter } from 'next/router';

function Menu() {

  const router = useRouter(); // Use the useRouter hook to access the router object
  const currentPageURL = router.asPath;
  console.log(currentPageURL);
  return <MenuComponent/>
}

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

How to define an index signature in Typescript that includes both mandatory and optional keys

I am on a quest to discover a more refined approach for creating a type that permits certain keys of its index signature to be optional. Perhaps this is a scenario where generics would shine, but I have yet to unlock the solution. At present, my construc ...

Send the context parameter value of Unified Service Desk to a JavaScript web resource in CRM

Currently, I am working on CRM 8.2 and Unified Service Desk 4.1. I have a specific requirement where I need to pass parameter values from within Unified Service Desk Data Parameters to a JavaScript Webresource. I have come across some resources that sugge ...

Saving data from Material UI forms in TypeScript

Is there an effective method for storing values entered into the text fields on this page? const AddUserPage = () => ( <div> <PermanentDrawerLeft></PermanentDrawerLeft> <div className='main-content'> < ...

I'm having trouble accessing the outcome from within the function

Having trouble getting the result to return inside a function for my basic rock paper scissors game. I've tried everything, including console logging the compare and putting it inside a variable. Strange enough, console.log(compare) is returning und ...

Alternate routing based on conditions in Angular

I've used the "$urlRouterProvider.otherwise('{route here}')" syntax in angular to create a catch-all route in Angular UI-Router. One thing I'm curious about is whether it's possible to have conditional "otherwise" routing based o ...

Adding a type declaration to the severity property in React Alert - A guide to Typescript

I've developed a type declaration object for the incoming data, but no matter what I try to define as the type for the property "severity", it's not happy. The options it wants (as displayed below) don't seem feasible. I'm curious if th ...

Tips on saving content that changes automatically

I am curious about the best way to store dynamically displayed HTML content. For example, when a certain element is clicked on a website, I want text to appear elsewhere on the page. One idea I had was to create a variable in a JavaScript/jQuery script to ...

What is the process for creating two columns with an input box beneath them?

I am facing a challenge with my code. I am struggling to create the desired design where there are two columns and below them an input box that will be displayed when a button is pressed. The design I am aiming for can be viewed here: enter image descripti ...

Is there a method to globally import "typings" in Visual Code without having to make changes to every JS file?

Is there a method to streamline the process of inputting reference paths for typings in Visual Studio Code without requiring manual typing? Perhaps by utilizing a configuration file that directs to all typings within the project, eliminating the need to ...

I encountered an error while trying to deploy my next.js project on Vercel - it seems that the module 'react-icons/Fa' cannot be found, along with

I'm currently in the process of deploying my Next.js TypeScript project on Vercel, but I've encountered an error. Can someone please help me with fixing this bug? Should I try running "npm run build" and then push the changes to GitHub again? Tha ...

Error Alert: Next.js TypeScript is reporting that the necessary packages are missing from your setup

As I work on developing a basic Next.js website using their TypeScript starter, everything was going smoothly with the 'yarn dev' command. However, out of nowhere, I started encountering an error message whenever I tried to run 'yarn dev&apo ...

Difficulty in submitting the information on the form

I recently had a question similar to this one, but unfortunately it was closed due to the length of the code. I'll try to keep this brief. My partner and I created a form, however, all the <Select> inputs are being sent as "undefined" in the HT ...

Why is it not possible for me to choose an element after it has been placed within a grid component?

Struggling to eliminate the blur effect on an image inside a grid element? It seems modifying the properties of an element within a grid class is causing some issues. To simplify, I conducted a basic test: I managed to change the ppp2 class when hovering ...

The split() function returns a string that remains unaltered and intact, without any

I am attempting to separate this string: 120,00 m² into two distinct parts like this: 120 m² This is the code I have been using: var test = jQuery('#wpsight-listing-details-3 .span4:nth-child(4) .listing-details-value').html(); var pa ...

Using VueJs's createElement() to dynamically insert HTML content

I am currently working on a component that converts all icons to SVG format. By the end of my code, I have included the following: return createElement('i', '<SVG>CODE</SVG>' ) In the spot where the SPA ...

using absolute URLs for image source in JavaScript

How can I output the absolute URLs of images in a browser window (e.g., 'www.mysite.com/hello/mypic.jpg')? Below is a snippet of my code: $('img').each(function() { var pageInfo = {}; var img_src = $(this).attr('s ...

Using AJAX to send a POST request with the PHP $_FILES superglobal while preventing the default form submission with the onclick

Seeking to implement a photo upload form using an AJAX script that is currently in place. Currently, I have the html form with a file input field. Upon submission, there is an onclick event triggering "PostForm(); return false;" This action directs to a ...

Send the output of MPDF back to the browser by utilizing JSON in combination with ExtJS

I am currently using mpdf to generate a PDF report in my PHP code. I have successfully been able to save the PDF file and view it by using Output($pdfFilePath), but now I need to send it back to the browser using JSON without saving it on the server. To ac ...

Mastering the Art of Trimming with Jquery

function DisplayDataForEdit(id) { $("#editContainer").slideDown("medium"); var parentId ='item'+ id; var colIndex = 0; var $row = $("#" + parentId).parent().parent(); $row.find('td').each(f ...

Any ideas on how to resolve this ajaxToolkit issue?

Just for your reference, here's what I'm trying to achieve: https://i.stack.imgur.com/GYaNz.jpg Error 1: Unknown server tag 'ajaxToolkit:CalendarExtender'. <ajaxToolkit:CalendarExtender FirstDayOfWeek="Monday" PopupPosition="Botto ...