score:2

Accepted answer

my final approach if it is useful for someone:

i followed @lucasoliveira approach but went a little bit further and this is what i did using ex-react-native-i18n but you can use whatever plugin you feel most comfortable with:

  • first i declared a helper method inside my component to return a single object with the complete translation

  • pass the translation object down to the "dummy" component

contaninercomponent.js

class containercomponent extends react.component {
  ...
  // load translation outside context.
  loadtranslation() {
    return {
      string1: i18n.t('key1'),
      string2: i18n.t('key2'),
      string3: i18n.t('key3')
    }
  }
  ...

  render() {
    return(
      <myawesomecomponent
         ...props
         translation={this.loadtranslation()}
      />
    );
  }
}

then, in the dummy component i set up a default translation, to fit the case in which the translation is not set and then i created a helper method to handle the possible not handled strings and avoid undefined values:

myawesomecomponent.js

const myawesomecomponent = ({ ..., translation }) => {

  const strings = handletranslation(translation);

  return (
      .... some jsx here ....
  );

};

const default_translation = {
  string1: 'your default string',
  string2: 'your default string',
  string3: 'your default string'
}

const handletranslation = (translation) => {
  if (translation === undefined) return default_translation;
  return {
    string1: (translation.string1 !== undefined) ?
        translation.string1 : default_translation.string1;

    string2: (translation.string2 !== undefined) ?
        translation.string2 : default_translation.string2;

    string3: (translation.string3 !== undefined) ?
        translation.string3 : default_translation.string3;
  }
};

and now the whole translation is safe to use from the "strings" variable.

hope it helps!

score:1

i would go for the second approach, cause the ability to define your object outside the component declaration, gonna make your component accepts an object, a string, a date, etc... allowing you to treat then later. doing that :

<myawesomecomponent 
   ...props
   translation={translation}
/>

means our code doesn't need to know that it is being rendered , as this will be your component responsibility


Related Query

More Query from same tag