Search code examples
reactjsi18nextreact-i18next

useTranslation hook react-i18next


why does it not work? I try to cut my translation path. How can I do that without passing whole path ("root.chapter.key")?

// json
{"root":
  "chapter": {
     "key": "Some text"
  }
}

const { t } = useTranslation('root')

const text = t('chapter.key')

// or

const { t } = useTransaltion('root.chapter')

const text = t('key')


Solution

  • First argument of useTranslation function must always be a namespace to load. If you want to shorten your JSON path, you can use keyPrefix option instead.

    const { t } = useTranslation('namespace', {
      keyPrefix: 'root.chapter'
    })
    
    const text = t('key');
    

    If you haven't explicitly defined your namespace, default value for it is translation.