21

I was wondering if there is any way to access what is the currently set locale with React-Intl?

Let's say I create this:

render() {
  return (
    <IntlProvider locale="en">
      <App>
    </IntlProvider>
  );
}

In App, I would like to do something like this, in order to access the locale that I passed to the IntlProvider

this.props.locale

Is there any way to do something like that?

Thanks.

alexmngn
  • 7,551
  • 14
  • 57
  • 117

2 Answers2

32

New answer - using hooks (see below for original)

import { useIntl } from 'react-intl';

const MyComponent: FC = () => {
    const intl = useIntl()
    return <div>{`Current locale: ${intl.locale}`}</div>
}

export default MyComponent

Old answer

You can get the current locale in any component of your App by simply accessing it from React Intl's "injection API":

import {injectIntl, intlShape} from 'react-intl';

const propTypes = {
  intl: intlShape.isRequired,
};

const MyComponent = ({intl}) => (
  <div>{`Current locale: ${intl.locale}`}</div>
);

MyComponent.propTypes = propTypes

export default injectIntl(MyComponent);
Bruford
  • 386
  • 2
  • 12
pierrepinard_2
  • 1,276
  • 11
  • 13
  • Almost 2yrs later and we now have a hook to do this @pierre do you want to update your answer? you can `const intl = useIntl(); console.log(intl.locale)` – Bruford Nov 29 '19 at 15:18
  • Hi @Bruford , thank you for this. I would gladly update my answer, but I must admit I haven't practiced hooks yet (I am currently working on other stacks). Could you please send me the updated answer with hook? – pierrepinard_2 Dec 02 '19 at 11:02
  • You could even do: const {locale} = useIntl() – Diogyn Dec 07 '20 at 22:48
2

Yes, if you want to access current locale in any child component, the best way would be to read context, because IntlProvider is providing a context. Define in your App or any other component the context you want to access:

App.contextTypes = {
    intl: PropTypes.object
};

Now you can read the current locale in your component like:

render() {
    return (
        <div>{this.context.intl.locale}</div>
    )
}
Borys Kupar
  • 1,338
  • 9
  • 21