stef000
stef000

Reputation: 123

React-Intl: I18n with arrays

I am currently working on a website which reads its data out of two json files (de.json and en.json). Now there is also a page where I need to read data either out of an english array or a german array depending on what language is selected (Each array is currently a simple js file with just the array inside of it and it just gets imported into the file where I need to read its data). The way it is working right now is by me checking if the locale is english and then using that array, however that solution is not clean.

const ResourcesMedia = [
    {
        title: 'sometitle',
        description: 'somedescription',
        href: 'somelink'
    },
    {
        title: 'sometitle',
        description: 'somedescription',
        href: 'somelink'
    }
  ]

export default ResourcesMedia;

There is another array like that just for the german version. Now depending on which language is selected I am mapping through the array and creating the components. However, currently I am checking what the locale is like that:

const mediaArray = locale === 'en' ? ResourcesMediaEn : ResourcesMedia

This is not the best way of doing it instead I would like to store the array in both the en.json and de.json file (or in two new files) and just let the IntlProvider decide which it should use. Is there a good way of doing that with React-Intl or do I need to implement that otherwise?

Upvotes: 1

Views: 3292

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281952

You can create an array wherein the values inside your arrays are keys and not actual strings and while you render them you can actually translate those

const ResourcesMedia = [
    {
        title: 'sometitleKey',
        description: 'somedescriptionKey',
        href: 'somelink'
    },
    {
        title: 'sometitleKey1',
        description: 'somedescriptionKey',
        href: 'somelink'
    }
  ]


render() {
   const {intl: {formatMessage: t}} = this.props;
   return ResourcesMedia.map(item => (
       <div>
          <div>{t(item.title)</div>
          <div>{t(item.description)</div>
       <div>

   ))
}

Upvotes: 1

Related Questions