Post

다국어 i18n에 변수 전달하여 사용하기

useTranslation 사용

1
2
3
4
5
6
7
8
import React from 'react'
import { useTranslation } from 'react-i18next'

export function MyComponent() {
  const { t } = useTranslation()

  t('total', { value: 10 })
}
1
2
// ko.json
"total": "합계: 개",

키 값 뒤에 객체를 전달하여 사용한다.

Trans Component 사용

1
2
3
4
5
6
7
8
9
10
11
12
13
import { Trans } from 'react-i18next'

function MyComponent({ person, messages }) {
  const { name } = person
  const count = messages.length

  return (
    <Trans i18nKey="userMessagesUnread" count={count}>
      Hello <strong title={t('nameTitle')}></strong>, you have{' '}
      9 unread message. <Link to="/msgs">Go to messages</Link>.
    </Trans>
  )
}
1
2
// en.json
"userMessagesUnread": "Hello <1></1>, you have 9 unread message. <5>Go to message</5>.",

Trans 컴포넌트로 JSX를 감싸서 사용한다.

참고사이트

[22-06-06 TIL] react i18next 사용법
Trans Component

This post is licensed under CC BY 4.0 by the author.