RemixのMetaFunctionで多言語対応したい
公開日:
ゴール
https://remix.run/docs/en/main/route/meta
// 公式より引用
import type { MetaFunction } from '@remix-run/node'; // or cloudflare/deno
export const meta: MetaFunction = () => {
return {
title: 'Something cool', // こいつらを多言語対応したい
description: 'This becomes the nice preview on search results.', // こいつらを多言語対応したい
};
};
Remix のMetaFunctionを使って設定できる、HTML の meta タグに設定する文章を多言語対応したい。
ライブラリのバージョン
@remix-run/node:v1.19.3remix-i18next:v5.3.0
試行錯誤
export const meta: MetaFunction = () => {
const { t } = useTranslation('news');
React Hook "useTranslation" is called in function "meta: MetaFunction" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use".
MetaFunctionの中で、当然hookは使えない
hookじゃない純粋な関数が API にないかを調べたが、役に立ちそうなものは見つからず。
結論
探したら公式ドキュメントに書いてあった。
https://github.com/sergiodxa/remix-i18next#translating-text-inside-loaders-or-actions
loader 関数のrequestから言語を取得して、翻訳してしまったものをMetaFunctionに渡すのがいいっぽい。
// loader
export async function loader({ request }: LoaderArgs) {
// loader関数の中で翻訳してしまう
let t = await i18n.getFixedT(request);
let title = t('My page title');
return json({ title });
}
// meta
export let meta: MetaFunction = ({ data }) => {
// metaは翻訳されたものをセットするだけ
return { title: data.title };
};
最後に
多言語対応は考えることが多くてとても大変
では
Bye