🗣️

react-i18nextの HTML改行

に公開

i18nextで改行や特殊文字を扱う方法について、いくつかのアプローチがあります。

react-i18nextのカスタムコンポーネントを使うと、HTMLタグを含めることができます。

実装内容

  1. 翻訳ファイルの更新

    • hero.json: タイトルに<br />タグを追加
  2. TransTextカスタムコンポーネントの作成

    • i18n/styled.tsxにTransTextコンポーネントを追加
    • デフォルトでサポートするタグ: <br />, <strong>, <em>, <i>, <p>
    • カスタムコンポーネントのサポート
    • 変数の埋め込み機能
  3. Sectionの更新

    • TransTextコンポーネントを使用してタイトルを表示
    • HTMLタグが正しくレンダリングされるように実装

使用方法

i18nの設定は既にtransSupportBasicHtmlNodes: trueで設定されており、すぐに使用できます。

locales/en-us/hero.json:

{
  "title": "New`<br />Dreaming`<br />Website"
}

Home.tsx:

import { TransText } from 'react-i18next';
-  <h1 className="relative text-5xl lg:text-6xl font-bold text-foreground leading-tight z-10">
-    <Trans i18nKey="hero.title" components={{ br: <br /> }} />
-  </h1>
    // 基本的な使用
    <TransText 
      i18nKey="hero.title" 
      as="h1" 
      className="text-4xl font-bold"
    />
    
    // カスタムコンポーネント付き
    <TransText 
      i18nKey="hero.title"
      components={{
        br: <br className="hidden md:block" />,
        strong: <strong className="text-accent" />
      }}
    />

Discussion