Link components in Next.js now automatically add the current path when working with nested dynamic routes, making it

How can I effectively handle nested dynamic routes and utilize the Next.js Link component?

Let's say I have 2 different file paths:

/pages/projects/index.js
<Link href={`/projects/${project.id}`} key={index}>
  <a>Project Name</a>
</Link>

Clicking on this will lead me to localhost:3000/projects/some-id/

and

/pages/projects/[pid]/index.js

I am struggling to understand how to add the path prefix of localhost:3000/projects/some-id/

<Link href={`/${router.pathname}/apple`}>
  <a>Business name</a>
</Link>

When using router.pathname, I get /projects/[pid]/apple, without the domain, and if I use router.asPath, I get the correct path but still without the domain. I'm not sure if adding the domain name directly into Link's href is the right approach.

Answer №1

Creating a nested dynamic route in Next.js

https://i.sstatic.net/Sup0Y.png

To begin, set up a basic link in your index.js file

import Link from 'next/link';

export default function Index() {
  return (
    <section>
      <h2>Index</h2>
      <Link href="/projectA">
        <a>Project A</a>
      </Link>
    </section>
  );
}

In the [projectId].js file, utilize the useRouter hook to access the current parameter and add it to your next route

import Link from 'next/link';
import { useRouter } from 'next/router';

export default function Project() {
  const router = useRouter();
  const { projectId } = router.query;
  return (
    <section>
      <Link href={`/${projectId}/2`}>
        <a>Project 2</a>
      </Link>
    </section>
  );
}

See a working example here

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

Struggling with incorporating GlobalStyles in the app.tsx file

I have been working with next13 and styled-components. Initially, everything seemed fine in my file globalStyles.ts, and all was functioning perfectly. However, I started encountering errors related to the import of <GlobalStyles/>. Specifically, th ...

In Vue.js, the properties of components are not defined

Currently, I am experiencing an issue where I am passing a props to one of my views, but when I print the result in console it shows up as undefined. This is causing difficulties as I am unable to make requests or consults. Here is the code snippet in ques ...

Passing parameters from a parent component to a child component and then back to the parent component

I have a unique custom component called InputWithButton that has a distinct structure: const InputWithButton = ({ type = "text", id, label, isOptional, name, placeholder = "", value = "", showPasswordReset, error, isDisabled, buttonLabel, handleChange ...

Customizing translations for various domains in Vue-i18n

Our app has a global reach and our company is undergoing a rebranding process in certain markets. For instance, we are currently known as "Acme Company" in the U.S. and Canada, but now we aim to be recognized as "Acme Company" in the U.S. and "Foo Company ...

Ways to navigate to a different page in React when a user clicks?

When working on my react app, I encountered an issue where the useHistory hook was undefined. How can I troubleshoot this problem and ensure that useHistory is properly defined? App.js import 'bootstrap/dist/css/bootstrap.css' import React f ...

What is the best way to verify that a check should have various attributes using chai-things?

Searching for a way to verify if an array in my mocha tests consists of an Object in my Node.js application, I discovered that with Chai-Things, I can use: [{ pet: 'cat' }, { pet: 'dog' }].should.include({ pet: 'cat' }) or ...

What is the process for generating a three-dimensional surface using 3D points in Three.js?

I am currently working on a project that involves creating simple 3D models using dots and lines, whether curved or straight. In the initial version of the project, I utilized SVG elements for rendering, smooth curves, and mouse events. Now, I am explorin ...

The pictures are not appearing on the production version of Next JS without any clear explanation

This puzzle is driving me crazy. After creating a website using Next.js 14, everything works perfectly in the development environment. However, once I build and start the application on my local machine, it runs smoothly but encounters issues when deploye ...

Tips for horizontally arranging a list with a flexible number of columns

I am attempting to create a horizontal list with 3 columns that automatically moves to a new line when the columns are filled. I have been trying to implement this using PHP but haven't had any success. If anyone could provide some guidance on how to ...

Verify that each interface in an array includes all of its respective fields - Angular 8

I've recently created a collection of typed interfaces, each with optional fields. I'm wondering if there is an efficient method to verify that all interfaces in the array have their fields filled. Here's the interface I'm working wit ...

Generate a fresh FileReader instance using the downloaded file via XmlHTTPRequest

I am attempting to use an XmlHTTPRequest object (level 2) downloaded through a "GET" request in order to create a new FileReader object. My goal is to create the FileReader object within the onload function of the xhr. The file, which is a .gz file, downl ...

Is there another way to implement this method without having to convert snapshotChanges() into a promise?

When trying to retrieve cartIdFire, it is returning as undefined since the snapshot method is returning an observable. Is there a way to get cartIdFire without converting the snapshot method into a promise? Any workaround for this situation? private asyn ...

I keep getting a 404 error when trying to use Internationalization (i18n) Routing

I want to implement multiple languages on my website using Next.js. I have made some configurations in next.config.js /** @type {import('next').NextConfig} */ const nextConfig = {} module.exports = nextConfig module.exports = { i18n: { l ...

Disappearances of sliding jQuery divs

I am currently working on a website using jQuery, and I have implemented a slide in and out div to display share buttons. The issue I am facing is that the code works perfectly on the first page, but on every other page, the div slides out momentarily and ...

Checking for a nonce in OIDC custom provider authentication for NextAuth

Currently, I am utilizing an IDP that necessitates a nonce for security purposes. In my NextAuth configuration, I have included the nonce in the authorization step with the following setup: import NextAuth, { NextAuthOptions } from 'next-auth' c ...

What is the best way to send an object key/value pair to a Vue template?

I've made progress on my component, but I'm facing an issue where the links are going to http://localhost:5173/[object%20Object]. It seems like I've reached a mental roadblock. This is what my component looks like: <template lang="p ...

Navigating between routes with React-router v4: A beginner's guide

There seems to be an issue with the routing functionality in my project. Currently, only the first component, Cloud, is being rendered on the / route. However, when I try to add other routes, they don't seem to work as expected. import React from &a ...

What steps can be taken to address the issue of the body-parser module being disabled in a node

My API is not functioning properly and I have observed that the body-parser module seems to be disabled in some way. Despite my efforts, I have been unable to find any information on this issue. Please refer to the image attached below for further details. ...

React: Struggling to retrieve the current inputbox event value

I have encountered an issue while working on a customized input box in react. Despite my efforts, I am unable to access the current event value. Here is the relevant code snippet: Parent Component:---------------------------------------------------------- ...

Issues with retrieving JSON data from Google Books API object

I've been working on retrieving data from the Google Books API and displaying the titles of the first 10 results on a web page. The site is successfully making the request, and I have a callback function that handles the results as shown below: funct ...