Next.js Discord

Discord Forum

How to next/link force prepend locale?

Unanswered
Polar bear posted this in #help-forum
Open in Discord
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

// 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;

0 Replies