nextjs14nextjs-dynamic-routingnext-link

Nextjs Link always replacing route instead of appending


I am facing issue with nextjs Link component. It is always replacing the url path with whatever is given in href field. For example: I have this folder structure for app routing:

   -> profile  
             -> page.tsx
             -> layout.tsx
             -> locations (folder)
                         -> page.tsx

Now, when I use Link inside page.tsx of profile folder to append /locations in the url. it instead replaces /profile with /locations.

what I expect

/profile -> /profile/locations (append)

what is actually happening

/profile -> /locations (replace)

I saw the documentation, according to which, the behavior which I am expecting should be happening by default without changing anything in replace prop. But even I set replace either true or false, I does not affect anything.


Solution

  • const pathname = usePathname();
    <Link href={`${pathname}/locations`}>Hello</Link>
    

    You should use the pathname to get the current path and append it to the new URL, as Link will navigate to the new URL directly without retaining the previous path.

    Using Next Js 14 version