react-i18next: DX: hook function returning translations with given key prefix
๐ Feature Proposal
const { t, tRoot} = useTranslationWithPrefix(keyPrefix: string)
Usage:
t('userModule.homeScreen.settingsSection.entry')
-> t('entry')
Hook function that provides t
function scoped to given translation key prefix, so that usage of translation strings with repeating prefix is simplified. Hook additionally returns tRoot
function which is regular, un-scoped t
function for cases when component needs to use some general purpose string.
Motivation
In React projects Iโve worked on, weโve repeatedly found this kind of function useful, as given component usually uses the same translation key prefix, which occasionally tends to get quite long. This function improves the developer experience by reducing copy-pasting of repeating key prefixes and reduces effect of spelling mistakes in long keys, that may be hard to spot.
Alternatives achieving the same goal:
- key prefix could be passed as an option to regular
useTranslation
hook. - function that wraps regular
t
function and returns a prefixed version of it.
Example
const { t, tRoot} = useTranslationWithPrefix('user.accountSettings.changePassword')
// Later
<h1>{t('title')}</h1>
<label>{t('label.newPassword')}</label>
<label>{t('label.repeatPassword')}</label>
<button>{tRoot('common.ok')}</button>
instead of
const { t } = useTranslation()
// Later
<h1>{t('user.acoountSettings.changePasaword.title')}</h1>
<label>{t('user.accountSetinngs.changePassword.label.newPassword')}</label>
<label>{t('user.acconutSettings.changePassword.lable.repeatPassword')}</label>
<button>{t('common.ok')}</button>
Iโm looking for your feedback, whether you consider this a worthy addition to react-i18next
API or whether you can already achieve this is some other way.
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Comments: 18 (14 by maintainers)
I am wondering if others find this feature any useful, like I did.
@jamuhl do you think itโs worth adding to i18next API? If yes, then I would try submit a PR upcoming week.