Next.js Discord

Discord Forum

Link goes to the wrong path?

Answered
American Sable posted this in #help-forum
Open in Discord
American SableOP
I've got a component that includes the following
// selected = Lessons
<Link href={`${selected}`}><Button>Next</Button></Link>


If I inspect the Element, I can see the following
<a href="Lessons">


If I click the href Link in the Element inspector in Chrome, or hover over my button, I can see the URL it will go to as http://localhost:3000/owners/bookables/new/Lessons which is correct.

However, if I actually click my Button, it takes me to http://localhost:3000/Lessons

Any idea whats going on?
Answered by American Sable
Created my own Link component

"use client"
import Link from "next/link";
import { usePathname } from 'next/navigation'
export default function Alink({children, href, ...props}){
    const pathname = usePathname()
    return (
        <Link href={`${pathname}/${href}`} props>{children}</Link>
    )
}
View full answer

10 Replies

American SableOP
My route structure for reference
American SableOP
8
can you try this?
<Link href={`/${selected}`}><Button>Next</Button></Link>

The slash at the beginning should tell it that it should be starting from the root rather than relative to the current path
oh yea i misread
then they prob need to add the full pathname
thats the way
American SableOP
Thanks, bit rubbish if i change my routes though, then i've got to refactor everything, rather than it being relative
American SableOP
Created my own Link component

"use client"
import Link from "next/link";
import { usePathname } from 'next/navigation'
export default function Alink({children, href, ...props}){
    const pathname = usePathname()
    return (
        <Link href={`${pathname}/${href}`} props>{children}</Link>
    )
}
Answer