useMessageFormatter
Handles formatting ICU Message strings to create localized strings for the current locale. Automatically updates when the locale changes, and handles caching of messages for performance.
install | yarn add @react-aria/i18n |
---|---|
version | 3.3.9 |
usage | import {useMessageFormatter} from '@react-aria/i18n' |
Introduction#
useMessageFormatter
wraps the intl-messageformat library to provide
a React Hook that integrates with the i18n system in React Aria. It handles formatting strings for the current locale,
updating when the locale changes, and caching of message formatters for performance. See the
intl-messageformat docs for information on how to create format strings.
API#
useMessageFormatter(
(strings: LocalizedStrings
)): FormatMessage
Example#
This example shows a simple component that displays a greeting, supporting both English and French. An object containing
the messages for each language is passed to useMessageFormatter
, which returns a formatMessage
function that can be
used to format the greeting. Two instances of the greeting component are rendered, using the I18nProvider
to specify the language to display.
import {I18nProvider, useMessageFormatter} from '@react-aria/i18n';
let messages = {
'en-US': {
'greeting': 'Hello, {name}!'
},
'fr-FR': {
'greeting': "Bonjour, {name}!"
}
};
function Greeting({name}) {
let formatMessage = useMessageFormatter(messages);
return (
<p>{formatMessage('greeting', {name})}</p>
);
}
<>
<I18nProvider locale="en-US">
<Greeting name="Devon" />
</I18nProvider>
<I18nProvider locale="fr-FR">
<Greeting name="Devon" />
</I18nProvider>
</>
import {
I18nProvider,
useMessageFormatter
} from '@react-aria/i18n';
let messages = {
'en-US': {
'greeting': 'Hello, {name}!'
},
'fr-FR': {
'greeting': 'Bonjour, {name}!'
}
};
function Greeting({ name }) {
let formatMessage = useMessageFormatter(messages);
return <p>{formatMessage('greeting', { name })}</p>;
}
<>
<I18nProvider locale="en-US">
<Greeting name="Devon" />
</I18nProvider>
<I18nProvider locale="fr-FR">
<Greeting name="Devon" />
</I18nProvider>
</>
import {
I18nProvider,
useMessageFormatter
} from '@react-aria/i18n';
let messages = {
'en-US': {
'greeting':
'Hello, {name}!'
},
'fr-FR': {
'greeting':
'Bonjour, {name}!'
}
};
function Greeting(
{ name }
) {
let formatMessage =
useMessageFormatter(
messages
);
return (
<p>
{formatMessage(
'greeting',
{ name }
)}
</p>
);
}
<>
<I18nProvider locale="en-US">
<Greeting name="Devon" />
</I18nProvider>
<I18nProvider locale="fr-FR">
<Greeting name="Devon" />
</I18nProvider>
</>