Search code examples
javascriptjsonreactjsreact-intl

How to access the IntlProvider's locale and messages in a component?


So my index.js has something like this:

import trFi from './translations/fi_FI.json';
import trSv from './translations/sv_SE.json';

ReactDOM.render(
  <IntlProvider
    locale={my_locale}
    messages={{ fi: trFi, sv: trSv }[my_locale]}
  >
      <Root />
  </IntlProvider>
);

And Root has multiple sub components and all. Now how can I get the provided locale and messages in these sub components? I know I can pass them as props to Root, which again passes them down, but my tree is rather deep and it's a pain in the ass to maintain this.

Is it possible to access this locale and messages passed to IntlProvider in the subcomponents directly?


Solution

  • As explained in the docs here, you can use a HOC (High Order Component) to wrap your components where they need to access internationalized data provided by <IntlProvider /> at the root of your component tree.

    Also, you have to use the <Formatted*> components to actually use that data for display.

    Here's an example from the docs above:

    import React from 'react';
    import { injectIntl, FormattedRelative } from 'react-intl';
    
    const PostDate = ({ date, intl }) => (
        <span title={ intl.formatDate(date) }>
            <FormattedRelative value={ date }/>
        </span>
    );
    
    PostDate.propTypes = {
        date: PropTypes.any.isRequired,
        intl: intlShape.isRequired,
    };
    
    export default injectIntl(PostDate);
    

    In addition to format* helpers, the config props, including messages andlocale can also be accessed directly down the tree via the same component prop intl (see the type definition intlShape here):

    const { locale, messages } = this.props.intl;