Skip to content

Commit

Permalink
Add and use I18n Link component
Browse files Browse the repository at this point in the history
  • Loading branch information
martinratinaud committed Mar 17, 2023
1 parent c03e2d7 commit 24da924
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/modules/I18n/components/LanguageSwitcher.tsx
@@ -1,5 +1,5 @@
import useTranslation from 'next-translate/useTranslation';
import Link from 'next/link';
import { Link } from 'modules/I18n';
import { useRouter } from 'next/router';

const ChangeLanguage = () => {
Expand Down
59 changes: 59 additions & 0 deletions src/modules/I18n/components/Link.tsx
@@ -0,0 +1,59 @@
import React from 'react';
import Link from 'next/link';
import { useRouter } from 'next/router';

import getConfig from 'next/config';

const { publicRuntimeConfig } = getConfig();
const permalinks: { [key: string]: { [key: string]: string } } =
publicRuntimeConfig.permalinks || {};

/**
* Formats permalinks
{
"/": {
"fr": "/accueil"
}
}
* into
{
"/fr/": "/fr/accueil",
"/en/accueil": "/"
}
*/
export const i18nFallbackUrls: { [key: string]: string } = Object.entries(
permalinks
).reduce(
(acc, [originalSlug, permalinks]) => ({
...acc,
...Object.entries(permalinks || {}).reduce(
(acc2, [locale, permalink]) => ({
...acc2,
[`/${locale}${originalSlug}`]: `/${locale}${permalink}`,
[`/en${permalink}`]: originalSlug,
}),
{}
),
}),
{}
);

const I18nLink = ({ href, locale, ...props }: any) => {
const router = useRouter();
const wantedLocale = locale || router.locale;
let i18nProps: any = {
href,
locale,
};

if (i18nFallbackUrls[`/${wantedLocale}${href}`]) {
i18nProps = {
href: i18nFallbackUrls[`/${wantedLocale}${href}`],
locale: false,
};
}

return <Link {...i18nProps} {...props} />;
};

export default I18nLink;
1 change: 1 addition & 0 deletions src/modules/I18n/index.tsx
@@ -1,3 +1,4 @@
export { default as useTranslation } from 'next-translate/useTranslation';

export { default as LanguageSwitcher } from './components/LanguageSwitcher';
export { default as Link } from './components/Link';
4 changes: 4 additions & 0 deletions src/modules/I18n/next.config.js
Expand Up @@ -43,6 +43,10 @@ module.exports = (nextConfig) => {

return {
...nextTranslateConfig,
publicRuntimeConfig: {
...nextTranslateConfig.publicRuntimeConfig,
permalinks, // add it to publicRuntimeConfig so it can be used by the Link component
},
async rewrites() {
const existingRewrites = nextTranslateConfig.rewrites
? await nextTranslateConfig.rewrites()
Expand Down

0 comments on commit 24da924

Please sign in to comment.