Skip to content

Instantly share code, notes, and snippets.

@oun
Last active November 19, 2024 17:50
Show Gist options
  • Select an option

  • Save oun/395fabdc24cacbd78b1b37422b07e2c2 to your computer and use it in GitHub Desktop.

Select an option

Save oun/395fabdc24cacbd78b1b37422b07e2c2 to your computer and use it in GitHub Desktop.
Use React-Intl API outside React component
import { IntlProvider } from 'react-intl';
const language = 'en';
// Usually messages is declared in another file.
const messages = {
greeting: 'Hello'
}
export const mesg = defineMessages({
greeting: {
id: 'greeting',
defaultMessage: 'Whats up'
}
};
const { intl } = new IntlProvider({ locale: language, messages: messages }, {}).getChildContext();
intl.formatMessage(mesg.greeting); // "Hello"
intl.formatNumber(1000); // "1,000"
@trevlar
Copy link
Copy Markdown

trevlar commented Jan 26, 2018

This is missing a closing paren on defineMessages.

@ozio
Copy link
Copy Markdown

ozio commented Feb 18, 2019

What is defineMessages and where can I get it?

UPD: ah, also should be imported from react-intl

@MrCuriosity
Copy link
Copy Markdown

outside components, such as in sagas
this may be helpful.

@bimal1331
Copy link
Copy Markdown

Is there anything wrong using this way inside the react components? It looks simpler than wrapping every component with injectIntl and then accessing intl prop. This way I can just import intl into every component.

@enrique-ramirez
Copy link
Copy Markdown

With the new update to react-intl, this no longer works. Anyone have an update?

@x-three
Copy link
Copy Markdown

x-three commented Nov 8, 2019

With the new update to react-intl, this no longer works. Anyone have an update?

https://github.com/formatjs/react-intl/blob/master/docs/API.md#createintl

@YoannBuzenet
Copy link
Copy Markdown

Hello, I found this createIntl method but I can't understand how to make it work in a Non React file.

Would anyone have a hint on how to implement it ?

@YoannBuzenet
Copy link
Copy Markdown

Ok, found out. When they write :

// Call imperatively
intl.formatNumber(20)

// Pass it to IntlProvider
{foo}

It means you can do one of them, both, but they are separate ways of using it. It's more : the first one OR the other.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment