Search code examples
reactjsi18nextreact-i18next

How to conditionally render text within react-i18next trans component


So I have the following trans component

<Trans i18nKey="userManagement:description">
    <span className="accountList-number">{{ accountsInvited }}</span>
    {' '}
    User(s) Invited,
    {' '}
    <span className="accountList-number">{{ accountsRegistered }}</span>
    {' '}
    User(s) Registered,
    {' '}
    <span className="accountList-number">{{ accountsAllowed }}</span>
    User(s) Allowed
</Trans>

with the corresponding userManagement.json translation file having the following line

{
    ...
    "description": "<0>{{accountsInvited}}</0> User(s) Invited, <4>{{accountsRegistered}}</4> User(s) Registered, <8>{{accountsAllowed}}</8> User(s) Allowed",
    ...
}

It displays like so.

I would like to actually make the "N user allowed" clause conditionally rendered. If accountsAllowed is null, then I would not show this clause since there is no limit on the number of users, but otherwise it should get displayed. On the react side, I suppose a good old ?: operator solves my problem, but I do not know how to change the translation file to also be conditional. Any helps would be appreciated. We are using trans component since those numbers are custom-styled and I prefer preserving the trans component if possible.


Solution

  • The context prop might be helpful. https://react.i18next.com/latest/trans-component#trans-props

    I didn't test the below code, so it may not work as expected 🙇

    <Trans i18nKey="userManagement:description" context={accountsAllowed ? "with-accountsAllowed" : null}>
        <span className="accountList-number">{{ accountsInvited }}</span>
        {' '}
        User(s) Invited,
        {' '}
        <span className="accountList-number">{{ accountsRegistered }}</span>
        {' '}
        User(s) Registered
        {accountsAllowed 
           ? (
             {', '}
             <span className="accountList-number">{{ accountsAllowed }}</span>
             User(s) Allowed
           )
           : '.'
        }
    </Trans>
    
    {
        ...
        "description": "<0>{{accountsInvited}}</0> User(s) Invited, <4>{{accountsRegistered}}</4> User(s) Registered, <8>{{accountsAllowed}}</8> User(s) Allowed",
        "description_with-accountsAllowed": "<0>{{accountsInvited}}</0> User(s) Invited, <4>{{accountsRegistered}}</4> User(s) Registered.
        ...
    }