Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Link in NextJs appends to current path but want to replace

Let's say the current url looks like this: localhost:3000/foo/hello and hello being a dynamic route. I have a Link Component with href={'/something/test'} and when clicking it I want to get to: localhost:3000/something/test, with test being a dynamic route.

But Clicking on that Link gets me to localhost:3000/foo/something/test instead of localhost:3000/something/test. The href just gets appended to the current path /foo

Removing the dynamic segment in the href (now being href={'/something'}) from the Link, gets me to localhost:3000/something.

Should I use useRouter in this instance or is there some way to do it with Link?

#in /foo/[test1]#

export default function Home(){
    return(
       <Link href={`/something/test`}> Click me</Link> // should get me to localhost:3000/something test
    );
}

# in /something/[test2]
export default function Page(){

    const { query } = useRouter();

    return(
       <div>
          {query.test2}
       </div>
    );
}

Clicking on the Link gets me to localhost:3000/foo/something/test which is not a defined route.

like image 225
Allleex Avatar asked Dec 07 '25 04:12

Allleex


2 Answers

Yes you can do this with Link. All you need to do is add ../ to href. Next treats this like any terminal. So to get localhost:3000 you could do href = {"../../something/test"}

like image 129
Hamilton Hardy Avatar answered Dec 08 '25 19:12

Hamilton Hardy


This will get you through where you want to.

export default function Home(){
    const pathname = "something/test"
    return(
       <Link href={"/" + pathname}> Click me</Link> // should get me to localhost:3000/something test
    );
}
like image 29
zemunkh Avatar answered Dec 08 '25 19:12

zemunkh