CodeBlanks Logo Icon CodeBlanks

Language switching

Learn language switching and persistence.

Language switching

To switch language you call i18n.changeLanguage('tr'). useTranslation returns this as i18n. When the call fires all components re-render automatically; the new language takes over.

Example: const { t, i18n } = useTranslation(); <Button onPress={() => i18n.changeLanguage('en')} />. Here tapping the button switches to English. The language choice is usually shown in a menu: Turkish, English, German. To make it stick you write it to AsyncStorage; on launch you read it from there. This way the user sees their preferred language every time.

Making the language choice stick

To make the language choice stick you use AsyncStorage. When the user picks a language you write AsyncStorage.setItem('lang', 'tr'). On launch you read AsyncStorage.getItem('lang') and apply it with i18n.changeLanguage.

Example: useEffect(() => { AsyncStorage.getItem('lang').then(l => { if (l) i18n.changeLanguage(l); }); }, []). This loads the saved language on every launch. If no save exists the default language is used. This pattern keeps the user experience consistent; the same language shows every time.

Practice Write a language switch button

Write a TouchableOpacity. Take i18n from useTranslation. In onPress call i18n.changeLanguage('en'). Show "English" in a Text inside.

Starter code

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

function LangButton() {
  // get i18n and call changeLanguage in onPress
  return (
    <TouchableOpacity onPress={() => {}}>
      <Text>English</Text>
    </TouchableOpacity>
  );
}

Sample solution

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

function LangButton() {
  const { i18n } = useTranslation();
  return (
    <TouchableOpacity onPress={() => i18n.changeLanguage('en')}>
      <Text>English</Text>
    </TouchableOpacity>
  );
}

Questions and answers

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

1 Which call switches the language?

App.js
i18n.?
  • switch
  • translate
  • changeLanguage Correct answer
  • setLang

Explanation: changeLanguage switches the language.

2 Match each flow piece to its role

Term Meaning
changeLanguage Switches language
AsyncStorage Stores the choice
getItem Reads the record
setItem Writes the record

3 changeLanguage call

Question
i18n.____('tr');
Answer
i18n.changeLanguage('tr');

Explanation: changeLanguage switches the language.

All lessons in Expert