In a previous post, Creating a multilingual website with Gatsby, I built kodou.me. Kodou has a Japanese and and English version. The post was a bit long so I didn’t talk about some of the utilities I used and how to build the site’s navigation menu.
In our previous post, we built a site in Japanese and English. The site’s default language is English. This means we have two URL types:
kodou.me/ja/team
kodou.me/team
The different page versions are written in Cosmic JS. We make Gatsby aware of the languages we use in /config/languages
. In gatsby-node.js
, we create our pages by using templates which we populate with data from Cosmic JS.
Here’s a simplified version of what the team-members
array returned by Cosmic JS might look like.
After we received the teamMembers
we create two objects jaTeamMembers
and enTeamMembers
. We populate templates/team
with jaTeamMembers
to create /ja/team
and enTeamMembers
to create /team
.
It’s important to be a good web citizen and make the sites we create accessible. So the first thing we need to do is add our languages to our site’s metadata. It might also help you get more targeted search results.
In our Gatsby application we also pass down to our templates the current language in the page’s context.
Now we can access lang
in our templates
The Intl API is used for string comparison, number formatting, and date and time formatting. It has a lot of cool features which we won’t explore here. We will simply use it here to display dates in the appropriate format.
We are adding the react-intl
package in our Layout
file.
When the page is generated in English, <FormattedDate>
will return Monday, December 9, 2019
. When the page is generated in Japanese <FormattedDate>
will return 2019年12月9日月曜日
.
You can see that in Layout
we have a Header
component. We pass all the language information to the header except the current language prop. We don’t pass it because I want to show you another way to the page’s current language.
And that’s it, you have a navigation menu in different languages which adapts its links according to the user’s current language. If you want to check out the utility functions I built they are available in the GitHub repo.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!