-
-
Save inadeqtfuturs/5281c16d825208fb36fec0ecb79d4d65 to your computer and use it in GitHub Desktop.
automatic i18n routing with NextJS's Link component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://alexchristie.dev/garden/13-i18n-next-link | |
// automatic internationalized links and routing using NextJS's Link component and app router | |
import type { ComponentProps } from 'react'; | |
import React from 'react'; | |
import Link from 'next/link'; | |
import { useParams } from 'next/navigation'; | |
const defaultLanguage = 'en'; | |
export type I18NLinkType = Omit<ComponentProps<typeof Link>, 'as'> & { | |
isAnchor?: boolean; | |
href: string; | |
}; | |
function getPath(path?: string | null) { | |
if (!path) { | |
return ['en', '']; | |
} | |
const pathArray = path.split('/').filter((x) => !!x); | |
if (pathArray.length === 0) { | |
return ['en', '']; | |
} | |
const [lang, ...restPath] = pathArray; | |
if (languageArray.includes(lang)) { | |
return [lang, restPath.join('/')]; | |
} | |
return ['en', pathArray.join('/')]; | |
} | |
function getPrefixedUrl(href: string, currentLanguage: string) { | |
if (/^((http|https):\/\/)/.test(href)) { | |
return href; | |
} | |
const [, tail] = getPath(href); | |
if (currentLanguage === defaultLanguage) { | |
return `/${tail}`; | |
} | |
return `/${currentLanguage}/${tail}`; | |
} | |
function I18NLink({ children, href, isAnchor, ...props }: I18NLinkType) { | |
const params = useParams(); | |
const currentLanguage = (params?.lang as string) || defaultLanguage; | |
const prefixedHref = getPrefixedUrl(href, currentLanguage); | |
if (isAnchor) { | |
return ( | |
<a href={prefixedHref} {...props}> | |
{children} | |
</a> | |
); | |
} | |
return ( | |
<Link href={prefixedHref} {...props}> | |
{children} | |
</Link> | |
); | |
} | |
export default I18nLink; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment