3

I'm trying to call the formatMessage() API directly outside the comp w/o using the standard <FormattedMessage../> component.

const locale = 'en';
const messages= defineMessages({
    greeting: {
        id: 'app.greeting',
        message:"some message",
        defaultMessage: 'Hello,all',
        description: 'Greeting to welcome the user to the app',
    }
});
const { intl } = new IntlProvider({locale, messages}).getChildContext();
export function someFunc(key, values) {
   return intl.formatMessage({id:'greeting'});
}

well the above is static messages defined locally, however I have a translation files, en.json and ja.json globally stored that I would like to load the messages from. How can I do that using the defineMessages, so that when I call the formatMessage() I should be able to see the messages from the resp files depending on the locale selected... ideas appreciated!! Thanks!

GProst
  • 9,229
  • 3
  • 25
  • 47
user1234
  • 3,000
  • 4
  • 50
  • 102

2 Answers2

2

I don't know the format of your .json files, but you can reformat them (if needed) so each key in them has at least id and defaultMessage (details) and pass to defineMessages() function.

import enMessages from 'path/to/en.json'
import jaMessages from 'path/to/ja.json'
const localeMessages = locale === 'en' ? enMessages : jaMessages

const messages= defineMessages(localeMessages);

...
const { intl } = new IntlProvider({locale, messages}).getChildContext();
intl.formatMessage({id:'greeting'});
GProst
  • 9,229
  • 3
  • 25
  • 47
1

If using the react-router npm package, you can set the IntlProvider component (from the react-intl npm package) as the main route within your route definitions. This means that all the translations are passed down as props to your components, i.e. you could access a particular message with this.props.messages.myMessage:

import { IntlProvider, addLocaleData } from 'react-intl';
import en from 'react-intl/locale-data/en';

addLocaleData(en);
let locale = 'en-GB';
const messages = require("./i18n/" + locale + ".i18n.json");
const renderRoutes = ({ locale, messages }) => (
    <IntlProvider locale={locale} messages={messages}>
    ...
    </IntlProvider>
);
ReactDom.render((renderRoutes({ locale, messages })), this.container);
JoeTidee
  • 24,754
  • 25
  • 104
  • 149