How can I resolve the issue of path accumulation?
Answered
Turkish Angora posted this in #help-forum
Turkish AngoraOP
'use client';
import { usePathname, useRouter, useParams } from 'next/navigation';
const links = [
{ name: '채팅방', href: 'chatrooms' },
{ name: '게시물', href: 'boards' },
{ name: 'ìœ ì €', href: 'user' },
];
export default function ContentTab() {
const pathname = usePathname();
const params = useParams();
const { replace } = useRouter();
const { slug } = params;
return (
<nav>
<ol className="flex">
{links.map((link) => (
<li
onClick={() => replace(`${pathname}/${link.href}`)}
key={link.name}
>
{link.name}
</li>
))}
</ol>
</nav>
);
}I'm using Optional Catchall segment like this [[...slug]]
How can I resolve the issue of the path accumulating every time I click on a tab?
21 Replies
Turkish AngoraOP
page hierarchy
Siberian
consider rewriting your url
is it needed to have
[[...slug]] there?Turkish AngoraOP
yeah cuz i want to route search/chatrooms, search/board and search
Siberian
but that slug is inside search route already
Turkish AngoraOP
[[...slug]]
import SearchModal from '../_components/SearchModal';
export default function Search({
params,
}: {
params: { slug: string };
}) {
const { slug } = params;
return (
<SearchModal>
{slug[0] === ''&&<div>Search keyword</div>}
{slug[0] === 'chatrooms'&&<div>chatrooms</div>}
{slug[0] === 'boards'&&<div>boards</div>}
{slug[0] === 'user'&&<div>user</div>}
</SearchModal>
);
}I want to render different components in the modal based on the slug
I used the Optional Catchall segment to account for cases where the slug is not present
Siberian
ohh
its due to replace
as for now you have your
localhost:3000/search/chatrooms as a pathname and you replace it with pathname + hrefTurkish AngoraOP
yup
Siberian
try out
onClick={() => replace(`${link.href}`)}Turkish AngoraOP
By doing that, 'search' won't get appended
like this
Siberian
Seems like the only way is to either hardcode that or remove last part from pathname
Turkish AngoraOP
hmm...
Siberian
or
Answer
Siberian
you could do something like this
onClick={() => replace(slug[0] ? pathname!.replace(slug[0], link.href) : (`${pathname}/${link.href}`))}You may correct above to fit your needs, as I was doing it as simple as possible