CodeBlanks Logo Icon CodeBlanks

Summary - Internationalization

Combine i18next, useTranslation and language switching to write a multilingual app.

Summary - Internationalization

In this group you saw i18n, i18next, translation files, useTranslation and language switching. A multi language app works like this: i18next.init starts it, translations live in JSON files, components get t through useTranslation, the user picks a language with changeLanguage.

In the last lesson you will write a component that joins all pieces. It will use useTranslation, translate a string and hold a language switch button. This way you see the multi language flow end to end.

Practice Write a multi language component

Write an App component. Take t and i18n from useTranslation. Show t('greeting') in a Text. In a TouchableOpacity's onPress call i18n.changeLanguage('en').

Starter code

App.js
import React from 'react';
import { Text, TouchableOpacity, View } from 'react-native';
import { useTranslation } from 'react-i18next';

function App() {
  // add useTranslation and components
  return <View />;
}

Sample solution

App.js
import React from 'react';
import { Text, TouchableOpacity, View } from 'react-native';
import { useTranslation } from 'react-i18next';

function App() {
  const { t, i18n } = useTranslation();
  return (
    <View>
      <Text>{t('greeting')}</Text>
      <TouchableOpacity onPress={() => i18n.changeLanguage('en')}>
        <Text>EN</Text>
      </TouchableOpacity>
    </View>
  );
}

Practice Extend the translation file

Write the content of a tr.json. The "greeting" key carries "Merhaba", the "farewell" key carries "Hoşça kal".

Starter code

App.js
{
  // add translation keys here
}

Sample solution

App.js
{
  "greeting": "Merhaba",
  "farewell": "Hoşça kal"
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which method switches the language?

App.js
i18n.changeLanguage(?)
  • changeLanguage Correct answer
  • useTranslation
  • init
  • fallbackLng

Explanation: changeLanguage switches the language.

2 Match each piece to its role

Term Meaning
i18next.init Initialization
useTranslation Gives t
changeLanguage Switches language
tr.json Turkish strings

All lessons in Expert