Search code examples
javascriptreact-nativetranslationi18n-js

Add styling to translation string in i18n-js React Native


I use i18n-js for translation purposes in my React Native app. But I cannot get any styling like different colors, bold etc. to my translations.

This is my en.js:

import {Text} from "react-native";

  const highlightText = (string) =>
    string.split(" ").map((word, i) => (
      <Text key={i}>
        <Text style={{ backgroundColor: "#ECEAFF", color: "#5F5C7E" }}>
          {word}
        </Text>
      </Text>
    ));

const en = {
   testTranslation:`This Text has some styling to it: ${highlightText("<h1>Hello</h1>")} isn't that pretty?`,

I use the translation on my screen like this:

import i18n from "i18n-js";
import { de } from "../../../locales/de";
import { en } from "../../../locales/en";
import { fr } from "../../../locales/fr";

i18n.fallbacks = true;
i18n.translations = { en, de, fr };

...
 <Text>
     {i18n.t("testTranslation")}
 </Text>

The outcome is this:

This Text has some styling to it: [object Object] isn't that pretty?

Any help how to style the text is much appreciated!


Solution

  • You can use syntax something like this

    Create 3 string in translation file. Example

    in translation files

    str1: 'this is"
    str2: 'bold'
    str3: 'copy'
    

    Now you can do something like

    <>
      <Text>{i18n.t(str1)}</Text>
      <Text className="boldStyle">{i18n.t(str2)}</Text>
      <Text>{i18n.t(str3)}</Text>
    <>
    

    There are other patterns for the same. but this is clean and small