How to next/link force prepend locale?
Unanswered
Polar bear posted this in #help-forum
Polar bearOP
Hello All.
Is there a quick way or Next js way to prepend locale with every link?
Manually add the locale from router to the <Link href="/${locale}/link">. But for that I have to add it in every link or create a custom component that has Link and I can use Locale there so I don't need to be do it for every link. For Instance
Is there a quick way or Next js way to prepend locale with every link?
Manually add the locale from router to the <Link href="/${locale}/link">. But for that I have to add it in every link or create a custom component that has Link and I can use Locale there so I don't need to be do it for every link. For Instance
// components/NavLink.js
import Link from 'next/link';
import { useRouter } from 'next/router';
const NavLink = ({ href, exact, children, ...props }) => {
const { pathname } = useRouter();
const isActive = exact ? pathname === href : pathname.startsWith(href);
return (
<Link href={`/${locale}/${href|`} {...props}>
<a className={isActive ? 'active' : ''}>{children}</a>
</Link>
);
};
export default NavLink;2 Replies
Polar bearOP
local prop with Next/link is not working
The url display same without locale
The url display same without locale
Sun bear
probably the best way is to create your own component that gets your locale from url, state, localstorage etc. and just prepend it dynamically.
"use client"
import Link, {LinkProps} from "next/link"
import useLocale from "your-custom-hook"
export default function LocaleLink({href, children, ...props}: LinkProps) {
const {locale} = useLocale()
return <Link href={`${locale}/${href}`}>{children}</Link>
}