react-intlbabel-plugin-react-intl

How to add locale data dynamically using React Intl?


Am using React-intl for internationalization of an UI Util Library. The library has a folder say i18n wherein I place json files for different locales.If the user of this library want to add support for additional locales, he/she can place additional json file with key/value pairs for the respective locale.

But React-intl requires to import and addLocaleData for the respective locale in prior.For example,

import fr from 'react-intl/locale-data/fr';
addLocaleData([...fr]);

Is there a way to addLocaleData and import the locale library for the respective locale dynamically in React-intl?


Solution

  • Hey I have done this now, as described below and its working :-)

    const possibleLocale = navigator.language.split('-')[0] || 'en';
    addLocaleData(require(`react-intl/locale-data/${possibleLocale}`));
    

    Here, the locale is fetched from the browser through navigator.language. Hope this helps :-)