loading...

re: Multilingual website with Gatsby and Contentful - Part 2 VIEW POST

TOP OF THREAD FULL DISCUSSION
re: I'm using gatsby-plugin-intl aswell. How do you go about mapping through an array that is translated? Example: { "contact" : "Kontakt", "bio...
 

Hi!

I have created the same kind of data in my intl file :

{
    "title": "Gatsby English",
    "description": "Project description",
    "author": "@louisbertin",
    "hello": "Hi people!",
    "welcome": "Welcome to your new Gatsby site.",
    "title_page2": "Page two",
    "hello_page2": "Hi from the second page",
    "go_page2": "Go to page 2",
    "welcome_page2": "Welcome to page 2",
    "go_back": "Go back to the homepage",
    "footer_build": "Built with",
    "test": [
        "hello",
        "world"
    ],
    "notfound": {
        "header": "NOT FOUND",
        "description": "You just hit a route that doesn't exist... the sadness."
    }
}

If I try to console.log(intl.messages) in one of my components I can see that react-intl not return an array of string but it creates multiple keys based on the number of items in the array :

Postgres issue on startup

So, you can create an array based on the object keys :

  var test = Object.keys(intl.messages).reduce((acc, item) => {
    if (item.includes("test")) {
      return [...acc, intl.messages[item]]
    }
    return acc
  }, [])
  console.log(test)

It returns :

["hello", "world"]

Now you can loop through this array and display all your data 🙂

Or.. if you know the number of items in your list (not recommended but faster) :

{[0, 1].map(index => (
   <FormattedMessage id={`test.${index}`} />
))}
 

Thank you for the answer! I ended up doing something similar: spectrum.chat/gatsby-js/general/us...

Code of Conduct Report abuse