简体   繁体   中英

using react-intl to translate a message key outside a component

I'm using the react-intl library for internationalization. Inside a component, I use the injectIntl HOC to translate message keys:

import {injectIntl} from 'react-intl';

const Component = props => (
    const message = props.intl.formatMessage({id: 'message.key'});
    // remainder of component omitted
);

export default injectIntl(Component);

Is it possible to get a message translation if I'm not inside a component?

Yes it is! You have to setup you application to provide the intl object so that you can use it from outside react components. You will have to use the imperative API for these cases. You can do something like this:

import { IntlProvider, addLocaleData, defineMessages } from 'react-intl';
import localeDataDE from 'react-intl/locale-data/de';
import localeDataEN from 'react-intl/locale-data/en';
import Locale from '../../../../utils/locale';

addLocaleData([...localeDataEN, ...localeDataDE]);
const locale = Locale.getLocale(); // returns 'en' or 'de' in my case

const intlProvider = new IntlProvider({ locale, messages });
const { intl } = intlProvider.getChildContext();

const messages = defineMessages({
  foo: {
    id: 'bar',
    defaultMessage: 'some label'
  }
});
const Component = () => (
  const componentMessage = intl.formatMessage(messages.foo);
);

I've done a different setup for me, but I guess this should work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM