What is internationalization (i18n) and why is it important for React applications?
Internationalization (i18n) is the process of designing software so it can be adapted to various languages and regions without engineering changes. For React applications, it enables reaching a global audience by providing content in users' native languages, enhancing user experience, engagement, and market reach. Only 25.9% of internet users were English speakers as of March 2020 (source), highlighting the need for multilingual support.
How do you set up internationalization in a React application using i18next?
To set up internationalization in React with i18next, create a new React app (e.g., using Create React App), install i18next and react-i18next, configure translations in a dedicated i18n.js file, and use the useTranslation hook in your components. Import the configuration in your index.js to make translations available throughout the app. (Guide)
How can you translate plain text in a React app using i18next?
Configure translation resources in i18n.js and use the t() function from the useTranslation hook to translate text. For example, t('welcome.text') retrieves the translation for the current language. (Details)
How does i18next handle interpolation and pluralization in React applications?
i18next supports interpolation for dynamic values and pluralization for different item counts. Define keys like text_one and text_other in your translation resources, and use t('interpolation_pluralization.text', { count: 5 }) to display the correct plural form. (Learn more)
How can you implement date and time translations in React using i18next?
Add a datetime key to your translation resources and use the t() function with a Date object and formatting options. For example, t('datetime', { date: new Date(), formatParams: { val: { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' } } }) formats the date according to the selected language. (Guide)
How do you enable switching between languages in a React app with i18next?
Implement UI elements (e.g., buttons) that call i18n.changeLanguage(languageCode) to switch languages programmatically. This updates the displayed content to the selected language. (Details)
What is lazy loading of translation files and how is it implemented in i18next?
Lazy loading allows translation files to be loaded on demand, improving performance for large applications. Use the i18next-http-backend module and configure loadPath to fetch translation JSON files from a specified directory (e.g., /locales/{{lng}}/{{ns}}.json). (Implementation steps)
How can Hygraph be used to manage and load translations for React applications?
Hygraph enables teams to manage multilingual content by localizing fields in the schema and selecting supported locales. Content can be queried via GraphQL using the locales parameter, allowing retrieval of translations for different languages. (Read more)
How do you query localized content from Hygraph using GraphQL?
Use the locales parameter in your GraphQL queries to specify desired languages. For example, products(locales: [en, fr]) retrieves product data in English or French, with fallback if the primary locale is unavailable. (Example)
What are the prerequisites for following Hygraph's React internationalization guide?
You should have a basic understanding of HTML, CSS, JavaScript, beginner-level React, and Node.js with npm or yarn installed. (Prerequisites)
How do you integrate Hygraph with React for content management?
Start by creating a free developer account on Hygraph, set up your project schema with localized fields, and use GraphQL queries to fetch and display content in your React app. (Integration tips)
What are the steps to enable and manage multiple locales in Hygraph?
In Hygraph, add locales via project settings, enable localization for fields in your schema, and input content for each language. You can then query and publish content for all supported locales. (Guide)
How do you load translations from Hygraph into a React application?
Use the graphql-request library to query Hygraph's API for localized content, then display the results in your React components. Example queries specify the desired locale and retrieve translated fields. (Example)
What topics are covered in Hygraph's guide on React internationalization?
The guide covers internationalization concepts, i18next setup, translation, interpolation, pluralization, date/time translations, lazy loading translation files, and integrating Hygraph for managing translations. (Topics)
Where can I find more resources and documentation on Hygraph and React internationalization?
i18next is a popular JavaScript internationalization framework that provides a complete solution for localizing products. It integrates seamlessly with React via the react-i18next library, supporting features like interpolation, pluralization, and server-side rendering. (Official site)
How does Hygraph support localization and multilingual content management?
Hygraph allows you to localize fields in your content schema, add multiple locales, and manage content for each language. You can query and publish content in different languages using GraphQL, making it easy to deliver multilingual experiences. (Read more)
Can I use Hygraph with other frameworks besides React?
Yes, Hygraph is framework-agnostic and can be integrated with various frontend and backend technologies, including Vue, Angular, and Node.js, thanks to its GraphQL API. (Supported frameworks)
What are the benefits of using Hygraph for internationalized React applications?
Hygraph streamlines multilingual content management, supports localization at the schema level, enables efficient querying via GraphQL, and integrates easily with React and i18next. This results in faster development, easier scaling, and improved global user experiences. (Blog post)
Features & Capabilities
What are the key capabilities and benefits of Hygraph?
Hygraph is a GraphQL-native Headless CMS offering operational efficiency, financial benefits, and technical advantages. Key features include Smart Edge Cache for performance, content federation, custom roles, rich text management, project backups, and enterprise-grade security. Notable results: Komax achieved 3X faster time-to-market, Samsung improved engagement by 15%, and Stobag increased online revenue share from 15% to 70%. (Customer stories)
How does Hygraph's Smart Edge Cache improve performance?
Smart Edge Cache enhances performance by accelerating content delivery and reducing latency, making Hygraph ideal for high-traffic and global audiences. It ensures faster load times and improved user experience. (Performance details)
What security and compliance certifications does Hygraph have?
Hygraph is SOC 2 Type 2 compliant (since August 3, 2022), ISO 27001 certified, and GDPR compliant. These certifications ensure robust security and adherence to international standards. (Security features)
What security features are included in Hygraph?
Hygraph offers granular permissions, SSO integrations, audit logs, encryption at rest and in transit, regular backups, and enterprise-grade compliance features such as dedicated hosting and custom SLAs. (Security details)
How does Hygraph measure and optimize API performance?
Hygraph monitors GraphQL API performance and provides practical advice for developers to optimize usage, ensuring reliability and speed for content delivery. (API performance)
What feedback have customers given about Hygraph's ease of use?
Customers praise Hygraph's intuitive editor UI, accessibility for non-technical users, and custom app integration. Hygraph was recognized for "Best Usability" in Summer 2023. (Try Hygraph)
How does Hygraph differentiate itself from other headless CMS platforms?
Hygraph stands out as the first GraphQL-native Headless CMS, offering content federation, Smart Edge Cache, user-friendly tools, and enterprise-grade security. It focuses on flexibility, scalability, and integration, setting it apart from platforms like Sanity, Prismic, and Contentful. (Comparison)
What are the KPIs and metrics associated with Hygraph's solutions?
Key metrics include time saved on content updates, system uptime, content consistency, user satisfaction scores, reduction in operational costs, speed to market, scalability, and performance during peak usage. (CMS KPIs)
How long does it take to implement Hygraph and how easy is it to start?
Implementation time varies by project. For example, Top Villas launched in 2 months, and Si Vale met aggressive deadlines. Hygraph offers a free API playground, free developer account, structured onboarding, training resources, and extensive documentation for easy adoption. (Case study)
Who is the target audience for Hygraph?
Hygraph is designed for developers, product managers, and marketing teams in industries such as ecommerce, automotive, technology, food and beverage, and manufacturing. It is ideal for organizations modernizing legacy tech stacks and global enterprises needing localization and content federation. (Enterprise solutions)
What is the primary purpose of Hygraph?
Hygraph empowers businesses to build, manage, and deliver digital experiences at scale. As a GraphQL-native Headless CMS, it eliminates traditional content management pain points and provides flexibility, scalability, and efficiency for modern workflows. (Product overview)
How does Hygraph handle value objections from prospects?
Hygraph addresses value objections by understanding customer needs, highlighting unique features (API-first, headless, GraphQL), demonstrating ROI (cost reduction, speed to market, scalability), and sharing success stories such as Samsung's improved engagement. (Samsung case study)
Can you share some customer success stories with Hygraph?
Yes. Komax achieved 3X faster time to market, Autoweb saw a 20% increase in website monetization, Samsung improved engagement, and Dr. Oetker enhanced their digital experience. More stories are available at Hygraph Customer Stories.
What is Hygraph's vision and mission?
Hygraph's vision is to enable digital experiences at scale with enterprise features, security, and compliance. Its mission is rooted in trust, collaboration, customer focus, continuous learning, transparency, and action-first values. (About Hygraph)
How does Hygraph contribute to achieving its vision?
Hygraph's GraphQL-native architecture, content federation, Smart Edge Cache, enterprise-grade features, and ease of use empower businesses to modernize content management and scale digital operations. (Contact Hygraph)
Technical Requirements & Support
What elements are included in a blog page model in Hygraph?
A Hygraph blog page model includes slug, category, tag, title, description, authors, publishing date, cover image, content, and SEO metadata. (Blog model details)
Where can I find a simple blog project using Hygraph?
How to Internationalize a React Application Using i18next and Hygraph
In this post, we will take a deep dive into how to internationalize a React Application using i18next and Hygraph.
Last updated by AagamÂ
on Nov 18, 2024
Originally written by Joel
Internationalization (or i18n) is a feature that is used to overcome the language barrier by providing support for several languages to users who use a certain software application or website. Only 25.9 percent of internet users were English speakers as of March 2020, emphasizing the need for multilingual websites and applications and emphasizing that you may be missing out on a substantial percentage of potential users.
In this article, we will see what internationalization is and how to implement it in our React applications with i18next.
#What is Internationalization and why is it Important
Internationalization (or i18n) is the process of ensuring that your website's platforms, processes, and architecture can accommodate and support many languages to allow you to build localized sites/apps. It is also the process of supporting different time zones, date formats, currencies, text directions, and more.
In simple terms, it is the process of ensuring that your website is set up to handle several languages and that your overall website design is capable of accommodating these numerous languages. This helps you to increase your reach to people all over the world.
I18next is a well-known JavaScript Internationalization library, it was developed in 2011 and has been maintained well till now. The main advantage of using this library is that it is quite mature and covers all possible use cases around internationalization, also it is framework agnostic and has more focus on Internationalization in general and not the framework in use, they have integrations available with almost every major framework and frontend/backend technology. So, if you have multiple codebases with different tech stacks or your projects keep changing, you can still use the i18next library across all different projects. Compared to other 18n libraries, i18next is quite mature and provides many features. More information on why i18next is unique can be found here.
Prerequisites
To follow along with this guide and code, you should have:
First, we'll set up our React application using Create React App (CRA), which is a quick way to start building a new single-page application in React. We can run the following command in our terminal:
npx create-react-app react-i18n-tutorial
Once that is successful, the next step would be to change the directory to the project and then start our server:
cd react-i18n-tutorial
npm start
Installing Dependencies
Next, we can install the dependencies required for our application. We would install two dependencies: i18next (the actual library), react-i18next (the React/React Native internationalization wrapper library). Let’s install all the dependencies at once by running the following command in our terminal:
Let’s learn how to translate normal/plain text from one language to another language. First, we need to configure i18next, we would do this by creating a dedicated file i18n.js in the src folder and pasting the following configuration code:
src/i18n.js
importi18nfrom'i18next';
import{ initReactI18next }from'react-i18next';
i18n
.use(initReactI18next)
.init({
resources:{
en:{
translation:{
welcome:{
text:'Welcome to this React Internationalization App',
},
},
},
fr:{
translation:{
welcome:{
text:"Bienvenue sur cette application d'internationalisation React",
},
},
},
},
lng:'en',
fallbackLng:'en',
interpolation:{
escapeValue:false
},
});
In this file, we first imported i18n from i18next and also initReactI18next from react-i18next, a plugin to ensure that i18next works with React. The next step was to initialize i18n by passing it an object of options. There are many configuration options you can pass to the initializer, and we're passing these for now:
resources: This contains the different translations that are available. We would eventually relocate our translations to a separate file/folder. Note: These translations contain both the key and the value; we utilize the key to obtain the value afterward. For example, in the above, text is the key, and Welcome to this React Internationalization App is the value of en (English) while Bienvenue sur cette application d'internationalisation React is the value for fr (French).
lng: This is used to provide the language we want to show or retrieve from the resources object. You can consider it to be the currently set language for the application.
fallbackLng: This option defines the fallback language in case some key is not recognized in the current language.
interpolation: Interpolation is one of the most commonly utilized features in I18N. It enables you to incorporate dynamic values into your translations. This would later be used to manage date formatting.
Using the t() Function in i18next
At this point, we have fully configured i18next on our React Application. The next step is to manage translations in our application. We need to include the i18n.js file we prepared earlier in our index.js file so it can be utilized throughout our application.
index.js
import'./i18n';
Now we can use translations. We utilize the t() method, which is derived from useTranslation and imported from react-i18next. Let's take care of this in our App.js file:
App.js
import{ useTranslation }from'react-i18next';
functionApp(){
const{ t }=useTranslation();
return(
<div>
<h2>{t('welcome.text')}</h2>
</div>
);
}
exportdefaultApp;
As you can see here, we made use of the key given in the resources file - welcome.text to get the actual value.
At this point when we load (via npm start) our app, we would see an output like this, and when we go to the i18n.js file to change the lng option to fr, the French text would be displayed.
Interpolation is one of the most commonly utilized features in i18n. It enables the incorporation of dynamic values into your translations and may be used in conjunction with Pluralization. In English, most plural nouns are produced by adding the s suffix, in many cases even the structure of various sentences can change when working with singular vs plural number of items For example - There is only one Article on this becomes There are 5 Articles on this for its plural. This pluralization is handled effectively by I18next.
To see interpolation in action let us add a new key interpolationpluralization as shown below, we have configured two sub-keys for text_one and text_other. Here, textone and textother are the new entries (see the _other suffix as that of plural and `one` as the singular).
resources:{
en:{
translation:{
welcome:{
"text":"Welcome to this React Internationalization App",
},
interpolation_pluralization:{
"text_one":"There is only one Article on this",
"text_other":"There are {{count}} Articles on this"
}
}
},
fr:{
translation:{
welcome:{
"text":"Bienvenue sur cette application d'internationalisation React",
},
interpolation_pluralization:{
"text_one":"Il n'y a qu'un seul article Ă ce sujet",
"text_other":"Il y a {{count}} articles sur ce sujet"
}
}
},
}
You can check out more examples and explanations here. I18next uses a {{placeholder}} for inserting dynamic values in the translations. We can now update our App.js file to make use of the text key to get the value:
This library also helps us with date/time translations and different types of formatting options. It will take care of things like how day names or month names are spelled in different languages and even formatting them differently. First, let us add a key to our configuration for managing the date-time translations
i18n.js
{
en:{
translation:{
...
datetime:"Today is {{val, datetime}}",
}
},
fr:{
translation:{
...
datetime:"Aujourd'hui c'est {{val, datetime}}",
}
}
}
Now in our App.js file all we need to do is to use this datetime key with the t() function
<p>{t('datetime',{date:newDate()})}</p>
We can even pass different formatting options to it, an example is shown below
We will implement the language-switching feature in this part. We can add buttons that would allow us to switch between languages programmatically. We just need to call i18n.changeLanguage function given by i18next and supply it the language code.
import{ useTranslation }from'react-i18next';
importi18nfrom'i18next';
functionApp(){
const lngs =[
{code:'en',nativeName:'English'},
{code:'fr',nativeName:'Francais'},
];
const{ t }=useTranslation();
return(
… existing code
<div>
{lngs.map((lng)=>{
return(
<button
className="m-4 p-2 bg-blue-600 rounded"
key={lng.code}
type="submit"
onClick={()=> i18n.changeLanguage(lng.code)}
>
{lng.nativeName}
</button>
);
})}
</div>
… existing code
);
}
exportdefaultApp;
Once this is done, and we load our app, the buttons will now appear and we can change the languages easily as seen below:
So far, we have been retrieving translations from our i18n.js file, which works great but is unsuitable for real-world applications with lots of translation keys. We can split these translations for different languages into dedicated JSON files, and lazy load them on demand. To do so, we'll need to use the i18next-http-backend module, let us install it first:
npm install i18next-http-backend
Once this is successful, the first step would be to import this package into the i18n.js file and then configure it:
i18n.js
importi18nfrom'i18next';
import{ initReactI18next }from'react-i18next';
importBackendfrom'i18next-http-backend';
i18n
.use(Backend)
.use(initReactI18next)
.init({
backend:{
loadPath:'/locales/{{lng}}/{{ns}}.json',
},
lng:'en',
interpolation:{
escapeValue:false,
},
});
The next step would be to move the translations to the public folder with the following structure:
Each translation.json file should contain translations for a single language, for example:
en/translation.json
{
"welcome":{
"text":"Welcome to this React Internationalization App"
},
"interpolation_pluralization":{
"text_one":"There is only one Article on this",
"text_other":"There are {{count}} Articles on this"
},
"datetime":"Today is {{val, datetime}}"
}
Now when we load our app, it will still look the same, but your translations are now lazy-loaded on demand. The code is better organized; if we want to support a new language, we just need a new translation JSON file. Note: We can also have multiple translation files thanks to the namespaces feature of i18next.
Hygraph is a cutting-edge content management platform that enables teams to provide content to any channel. If this is your first time exploring Hygraph, create a free-forever developer account and begin your first project. You may also find some tips on how to integrate Hygraph in React.
Let's look at how we can simply translate, publish, and manage material with several locales from a single piece of content using Hygraph, which maintains and loads translations with GraphQL. The first step would be to establish a project, and then construct a schema for the project, being sure to check the box next to Localize fields while creating each field, as seen below.
Once all fields have been created, the next step before you start inputting content would be to add the particular locales (languages) you want your application to support by going to settings → Locales → and then selecting the language as seen below:
At this point, we can start input data into these fields, but we first need to enable the particular languages we want on the right side so a field can be created for them
Editor's Note
You can read more on how to handle localization in Hygraph here
Loading Translations from Hygraph
Once you are done inputting all your content, you can publish. Let’s now see how to load those translations via their languages. In Hygraph querying is done with graphql-request and for us to do that in React, we first need to install the dependency by running the command below:
npm i graphql-request
Once it has successfully installed, the next step would be to import it into our App.js file, so we can now query the endpoint from Hygraph:
import{ request }from'graphql-request';
Querying with GraphQL
Let’s now see various ways we can query our endpoint, we can set a default locale (via its code) and a fallback in case the particular language is not available by passing in the (locales: [en, de]) parameter:
{
products(locales:[en, fr]){
id
title
description
}
}
This will give us our output in English since we have our content in English, but suppose there is no content found for en, it will then fetch content in fr. Here is the output:
{
"data":{
"products":[
{
"id":"cl0xocls20r3k0bmp2hfhb0ey",
"title":"Here is a flower",
"description":"This is a very beautiful flower, many people will love"
}
]
}
}
We can also get data for a particular language by entering that locale, as seen below:
Finally, the last step would be to load our translations into our react application using graphql-request:
In this guide, we learned about internationalization, and how to use i18next in a React application. We saw different features of internationalization like translation, interpolation, pluralization, date/time translations, lazy loading translation files, and finally wrapped up with Hygraph integration.
Blog Authors
Aagam Vadecha
Joel Olawanle
Share with others
Sign up for our newsletter!
Be the first to know about releases and industry news and insights.