Turner Hayes
Turner Hayes

Reputation: 1944

React-intl custom formatters

Is there a way to pass custom formatters for React-intl? I see that the <IntlProvider> has a formats prop, but looking at the docs for FormatJS, it looks like that only allows augmenting existing formatters (e.g. number, date). My current use case is a list of names, and I want to have it comma separated with the last item joined with a conjunction (e.g. Steve, Joe, Sandra, Judith and Jerry). Ideally, I'd just pass in a list (['Steve', 'Joe', 'Sandra', 'Judith', 'Jerry']) and the formatter would use the appropriate join form for the language. Is that currently supported?

Upvotes: 1

Views: 1858

Answers (1)

nemile
nemile

Reputation: 111

I think you could achieve this with the built in select formatter as follows:

const names = ['Steve', 'Joe', 'Sandra', 'Judith', 'Jerry'];

intl.formatMessage({id: 'layout'}, {
  names: names.map((name, index) => intl.formatMessage(
    {id: 'name'}, {
      name: name,
      position: index === names.length - 1 ?
        'last' : (index === 0 ? 'first' : 'inner')
    }
  )).join('')
});

And in your translations JSON file:

{
  "layout": "Here are the names: {names}",
  "name": "{position, select, first {} last {\u00a0and } other {, }}{name}"
}

This would allow you to change the separator regarding the position (considering certain languages are read from right to left). The join('') just concatenates all the "separator aware" names to build the enumeration string.

Note I used the unicode \u00a0 character for space because the usual space was ignored if placed first in the interpolated string.

Upvotes: 2

Related Questions