Search code examples
typescriptreact-typescriptreact-i18next

How to use React-i18next library with tailwind css and links without breaking sentence into parts


I have with problem with multi language translation using useTransalate.

When I have on a page a typical content like this: "By continuing, you agree to Terms and Conditions and accept Privacy Policy." I need that "Terms and Conditions" and "Privacy Policy" will be in links and in different colour. So the easiest way it to do this:

en.json

  "signup_you_agree": "By continuing, you agree to",
  "signup_terms_conditions": "Terms and Conditions",
  "signup_accept": "and accept",
  "signup_privacy": "Privacy Policy",

index.tsx

             <>
              <p className="font-light text-gray-500 dark:text-gray-300">
                {t('signup_you_agree')}{' '}
                <a
                  href="..."
                  className="font-medium text-primary-600 dark:text-primary-500 hover:underline"
                >
                  {t('signup_terms_conditions')}
                </a>{' '}
                {t('signup_accept')}{' '}
                <a
                  href="..."
                  className="font-medium text-primary-600 dark:text-primary-500 hover:underline"
                >
                  {t('signup_privacy')}
                </a>
                .
              </p>
            </>

But... To prevent problem with translations when sentence has breaks I need it to be more like this.

"signup_terms_privacy": "By continuing, you agree to <a href="...">Terms and Conditions</a> and accept <a href="...">Privacy Policy</a>."

Is there any way to it? Adding tailwind css and links to text from translation?

DangerouslySetInnerHTML is dangerous and it wont accept tailwind css or mui. I was looking for some extension for react-i18next but could find anything.


Solution

  • The way to do that is using Trans Component from react-i18next.

    It would look like:

              <Trans
                i18nKey="signup_terms_privacy"
                components={{
                  1: (
                    <a
                      href="..."
                      className="font-medium text-primary-600 dark:text-primary-500 hover:underline"
                    />
                  ),
                  2: (
                    <a
                      href="..."
                      className="font-medium text-primary-600 dark:text-primary-500 hover:underline"
                    />
                  )
                }}
              />
    

    With en.json

    "signup_terms_privacy": "By continuing, you agree to <1>Terms and Conditions</1> and accept <2>Privacy Policy</2>."