Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to access the current locale with React-Intl?

Tags:

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.

like image 620
alexmngn Avatar asked Jul 21 '17 15:07

alexmngn


People also ask

What is i18n in React?

Internationalization or i18n is the design and development of a product, application, or document content that enables easy localization for target audiences that vary in culture, region, or language. Thus, React i18n is concerned with localizing React applications for different locales.


1 Answers

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); 
like image 89
pierrepinard_2 Avatar answered Sep 28 '22 07:09

pierrepinard_2