0

I want to use formatMessage from react-intl (v5.25.1) for creating a string in order to use them later (in an event callback).

For example this for my message ("hp:single:monthlyPerfTooltip": "AZ letzter Bezugszeitraum: <b>{monthlyVal}</b>",, sorry, German):

const tooltipText = intl.formatMessage({id: 'hp:single:monthlyPerfTooltip'},
    {
         monthlyVal: intl.formatNumber(input.data.valueMonth, {minimumFractionDigits: 2, maximumFractionDigits: 2}),
         b: str => <b>{str}</b>
    });

Does not work: Argument of type 'ReactNode' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.ts(2345)

But I can see this example in the docs (with rich text formatting):

function () {
  const messages = defineMessages({
    greeting: {
      id: 'app.greeting',
      defaultMessage: 'Hello, <bold>{name}</bold>!',
      description: 'Greeting to welcome the user to the app',
    },
  })

  return intl.formatMessage(messages.greeting, {
    name: 'Eric',
    bold: str => <b>{str}</b>,
  })
}

More versions:

"@types/react-intl": "^3.0.0",
"typescript": "^4.6.3"

What am I doing wrong?

BairDev
  • 2,865
  • 4
  • 27
  • 50
  • The difference between your code and the sample from the doc is that in sample the `bold` is a _function_ that returns element. You could try to change your code accordingly: `b: str => {str}`. – tromgy May 13 '22 at 10:51
  • @tromgy Fixed this in the description, the error remains the same: `Argument of type 'ReactNode' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.ts(2345)` – BairDev May 16 '22 at 13:41
  • Perhaps it's how you define the message? I followed the examples in the doc and couldn't reproduce the problem. You can check this [stackblitz](https://stackblitz.com/edit/react-ts-cnispj?file=App.tsx) for reference. – tromgy May 17 '22 at 03:00
  • @tromgy I am using `` for the messages. They are simple key/value objects like `{hp:single:monthlyPerfTooltip: 'Some cool msg {monthlyVal}' [...]}`. Then I use `` on *top level*. Therefore I am using `intl.formatMessage({id: 'hp:single:monthlyPerfTooltip'}, ...values)` in my component. – BairDev May 20 '22 at 10:45
  • You should try to create a complete reproducible example, perhaps in codesanbox or stackblitz. – tromgy May 21 '22 at 13:54
  • @tromgy I have learned from this: https://codesandbox.io/s/react-intl-values-1jttq9 that the problem was in other parts of my code. Because `formatMessage` can return a string or a *ReactNode*, dependent on the values object. If I pass a mini-component in the values object, I can use the result in a template (like `{message}`), but not as string for `ìnnerHTML`. Therefore I need to rethink my approach for tooltips in general here. – BairDev May 31 '22 at 07:06

0 Answers0