Is there a way to access the current language using React-Intl?

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

Let's say I create this:

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

      

In an application, I would like to do something like this in order to access the language that I passed to IntlProvider

this.props.locale

      

Is there a way to do something like this?

Thank.

+3


source to share


2 answers


You can get the current locale in any component of your application simply by accessing it from the React Intl "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);

      

+2


source


Yes, if you want to access the current language in any child component, the best way is to read the context, because the IntlProvider provides the context. Define in your application 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, for example:

render() {
    return (
        <div>{this.context.intl.locale}</div>
    )
}

      

0


source







All Articles