DEV Community

Jonas Grøndahl
Jonas Grøndahl

Posted on

3

Multi language support in React Native apps

Hello everyone,

I had a look over at the following article to learn about how to create a multi language app in React Native:

https://medium.com/better-programming/creating-a-multi-language-app-in-react-native-9828b138c274

I thought to myself, there must be an easier way to do this. Let's make a Context provider and wrap the app inside of it:

import React, {useEffect, useState, useContext} from 'react';
import * as RNLocalize from 'react-native-localize';
const LanguageContext = React.createContext<>();

const translationGetters = {
  en: () => require('../lang/translations/en.json'),
  dk: () => require('../lang/translations/dk.json'),
};

export const LanguageProvider: React.FC = ({children}) => {
  const [language, setLanguage] = useState('en');

  useEffect(() => {
    const fallback = {languageTag: 'en', isRTL: false};
    const {languageTag} = RNLocalize.findBestAvailableLanguage(Object.keys(translationGetters)) ||
      fallback;

    setLanguage(languageTag);
  }, []);

  const value = {
    ...translationGetters[language](),
  };

  return (
    <LanguageContext.Provider value={value}>
      {children}
    </LanguageContext.Provider>
  );
};

export const useTranslation = () => useContext(LanguageContext);

In the above code, I'm using the react-native-localize to grab the language of the device and then use to access the right language key inside my getter function. Now every component can call useTranslation() and grab the text they need.

Question is though if the above code is capable of doing the same as the code in the link. I'm not using a memoize function but really I'm just outputting text so is it really needed?

Hope somebody can shed some light on this! And if not, hopefully the code above is helpful in your next React Native app that needs multi language support 😄

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Instrument, monitor, fix: a hands-on debugging session

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️