List formatting
When working with lists of items, you might want to format them as conjunctions or disjunctions.
Formatting aspects, like the used separators, differ per locale:
- "HTML, CSS, and JavaScript" in
en-US
- "HTML, CSS und JavaScript" in
de-DE
List formatting can be applied with the useFormatter
hook:
import {useFormatter} from 'next-intl';
function Component() {
const format = useFormatter();
const items = ['HTML', 'CSS', 'JavaScript'];
// Renders "HTML, CSS, and JavaScript"
format.list(items, {type: 'conjunction'});
// Renders "HTML, CSS, or JavaScript"
format.list(items, {type: 'disjunction'});
}
See the MDN docs about ListFormat
(opens in a new tab) to learn more about the options that you can provide to the list
function or try the interactive explorer for Intl.ListFormat
(opens in a new tab)).
Note that lists can can currently only be formatted via useFormatter
, there's no equivalent inline syntax for messages at this point.
To reuse list formats for multiple components, you can configure global formats.
How can I render an array of messages?
See the arrays of messages guide.
Accepted values
While Intl.ListFormat#format
(opens in a new tab) only accepts string
values, format.list
accepts a broader range of values that can be formatted:
string
number
boolean
ReactNode
null
undefined
Note that if you pass elements that are a non-primitive ReactNode
, the formatter will return a ReactNode
too.
import {useFormatter} from 'next-intl';
function Component() {
const format = useFormatter();
const users = [
{id: 1, name: 'Alice'},
{id: 2, name: 'Bob'},
{id: 3, name: 'Charlie'}
];
// Returns a `ReactNode`
return format.list(
users.map((user) => (
<a key={user.id} href={`/user/${user.id}`}>
{user.name}
</a>
))
);
}