Enhance your Next.js routing by appending to a slug/url using the <Link> component

In my Next.js project, I have organized my files in a folder-based structure like this:

/dashboard/[appid]/users/[userid]/user_info.tsx

When using href={"user_info"} with the built-in Next.js component on a user page, I expect the URL to dynamically point to

/dashboard/app_01/users/123123123/user_info
. However, it currently redirects me to /user_info which is not the desired location.

This is how the Next.js react component is structured:

'use client';

import Link from 'next/link';
import React from 'react';
import Image from 'next/image';


type sidebarbuttonprops = {
    text: string,
    to?: string,
    id: string,
    active?: string,
    disabled?: string[],
    icon?: string,
    getButtonValue: (buttonid: string) => void
}

export const SideBarButton = ({ text, to: link, id, active, disabled, icon, getButtonValue }: sidebarbuttonprops) => {
    let buttonActive: boolean = id == active ? true : false;
    let buttonDisabled: boolean | undefined = disabled?.includes(id);
    const handleClick = (e: React.MouseEvent<HTMLElement>) => {
        if (!buttonDisabled) {
            getButtonValue(id);
        }
    }

    return <Link className="sidebar-button" role='link' href={!buttonDisabled ? link! : ''} replace={false} onClick={handleClick}>
        <div className={`sidebar-button__container${buttonActive ? ' button_active' : ''}${buttonDisabled ? ' button_disabled' : ''}`} id={id}>
            <div className='sidebar-button__svg'>
                {icon != undefined && <Image src={icon!} alt="icon" width={25} height={25} />}
            </div>
            <div className='sidebar-button__text'>
                <span className='sidebar-button__span'>
                    {text}
                </span>
            </div>
        </div>
    </Link>;
}

The HTML generated for the link appears as follows:

<a class="sidebar-button" role="link" href="user_info">"[Some divs]"</a>

Even though hovering over the link displays the correct URL of

/dashboard/app_01/users/123123123/user_info
, clicking the link navigates to an incorrect section. When clicking the link inside DevTools, it directs me to the correct destination.

TL;DR: How can I dynamically add the user_info to the current URL without specifying the entire path?

Answer №1

Thanks to some helpful hints from eten, I was able to uncover the solution on my own for tackling this issue within next.js versions below 13.

If you're working with Next.js versions above 13, it's necessary to employ usePathname in order to access the current path and subsequently make modifications to it.

 import { usePathname } from 'next/navigation';

 export default function Page() {
     const current_path = usePathname(); // obtain current path
     ...

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

Executing a JavaScript function through C# code

Does anyone have a code snippet for calling a JavaScript function from C#? Here's the scenario: I have an ASP.NET page with an ASP button. When this button is clicked, I want to call a JavaScript function. For example: In my ASP.NET page, <but ...

aligning JSON information with JavaScript object

I am currently in the process of setting up a sample dataset in JSON format for a JavaScript tutorial that I'm going through. Here's how the data object looks in JavaScript: app.Book = Backbone.Model.extend({ defaults: { coverImage: ...

Why does Cloudinary fail to delete the tmp folder it creates after finishing the upload process?

Recently, I've been working on implementing an upload Post feature for my app. The process involves submitting a file from the frontend, sending it to the backend, and then uploading it to Cloudinary's cloud servers. However, before the upload to ...

What is the recommended default value for a file in useState when working with React and TypeScript?

Can anyone help me with initializing a file using useState in React Typescript? const [images, setImages] = useState<File>(); const [formData, setFormData] = useState({ image: File }); I'm facing an issue where the file is sho ...

Having trouble triggering drag events efficiently with d3-drag on SVG elements

drawAll refers to a two-dimensional array where each drawAll[i] element represents a drawing containing all the strokes. A stroke is essentially a string representing a series of 2D points that can be utilized to generate a <path>. I am currently at ...

Displaying queries using ajax in Rails

Can someone assist me in dealing with a particular issue? I am using ajax to refresh queries from the database dynamically each time there is a change in a search form. The main objective is to load N number of records based on the parameters selected in ...

What is the best way to create a dynamic graph in amcharts during runtime?

Below is the code for Multiple Value Axes: In this code, we aim to display a graph using dynamically generated random data. When executed, nothing will happen. <script> var chart; var chartData = []; // generate some random data within a different ...

Generating XML format from JSON using JavaScript

I am looking to create an XML format based on my JSON data, rather than converting it from JSON to XML. Here is an example of the JSON I want to convert to XML: var jsonData = { "Smart Shoes":{ "Product":"Smart Shoes", "Price":24.99, ...

What is the reason behind my resizer bar not changing color to green?

Whenever I resize the bar between the West and Inner Center areas, it turns green. However, the bar between the Inner Center and Inner South areas does not change color. How can I make it turn green when resizing, including adding the orange highlight for ...

What is the best way to convert JSON into a complex object in Typescript and Angular?

In my Typescript class for an Angular version 5 project, I have a JavaScript function that generates a style object. Here is the function: private createCircle(parameters: any): any { return new Circle({ radius: parameters.radius, ...

Is there a problem with renaming files using the multer module's filename options?

I can't figure out why this isn't functioning as intended. The file upload feature is operational, but the generated name consists of a long string like 04504a8b6c715f933110c8c970a8f6ad. What I need is for the filename to include the original nam ...

Leverage Firebase cloud functions to transmit a POST request to a server that is not affiliated with

Is it feasible to utilize a firebase cloud function for sending a post request to a non-Google server? It appears that being on the blaze plan is necessary in order to communicate with non-google servers. Essentially, I aim to perform a POST action to an ...

JavaScript: The delayed submission feature is malfunctioning

Visit this link When using JSFiddle, a strange list of errors is generated (see pic here). However, the auto-submit feature on my page works fine, but it lacks the specified delay. Thank you in advance for any assistance. <form id='formBlokUziv&a ...

Preventing special characters, numbers, and spaces from being used as the first character in a word in HTML with regular expressions

Is there a way to restrict users from inputting special characters, numbers, and spaces only in the first place of a word using regex in HTML? <label><span>Current Carrier</span></label> <input name='Current Carrier' t ...

Troubleshooting Node.js import module errors

I have just discovered two files that I created using the TS language specification manual (on page 111). The first file, called geometry.ts, contains the following code: export interface Point { x: number; y: number }; export function point(x: number, y ...

Creating custom shaders for YouTube videos within a Three.js userscript

I want to add a shader effect to YouTube videos. My current approach involves using Three.js to implement a shader on a video. Specifically, I am trying to adapt this example of applying a shader to a video (code available here) into a Tampermonkey usersc ...

Determining the class condition using AngularJS ng-class

I am working with an HTML element that contains AngularJS directives: <div class="progress"> <span ng-repeat="timeRangeObject in timeRangeObjects" style="width: {{timeRangeObject.percentage}}%" ...

SvgIcon is not a recognized element within the JSX syntax

Encountering a frustrating TypeScript error in an Electron React App, using MUI and MUI Icons. Although it's not halting the build process, I'm determined to resolve it as it's causing issues with defining props for icons. In a previous pro ...

The type '{ children: Element[]; }' does not include the properties 'location' and 'navigator' that are present in the 'RouterProps' type

Struggling to implement React Router V6 with TypeScript, encountering a type error when including Routes within the `<Router />` component. The error message indicates that the children property passed to the Router is of an incorrect type, despite u ...

Some files are missing when performing an npm install for a local package

My project is structured like this: ├── functions/ │ ├── src │ ├── lib │ ├── package.json ├── shared/ │ ├── src │ | ├── index.ts | | ├── interfaces.ts | | └── validator_cl ...