DEV Community

loading...

Discussion on: Multilingual website with Gatsby and Contentful - Part 2

Collapse
louisbertin profile image
Louis Bertin Author

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}`} />
))}
Collapse
zasuh_ profile image
Žane Suhadolnik

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