1

How can you conditionally remove surrounding text and whitespace (or not include rather) in a message? Let's use the example from the documentation.

<FormattedMessage
  id="app.greeting"
  description="Greeting to welcome the user to the app"
  defaultMessage="Hello, {name}!"
  values={{
    name: 'Eric',
  }}  
/>

If you wanted to get a version of this that just said 'Hello!', because the user forgot to fill in a name. Would you have a define a new message in the language files? Then evaluate whether the name variable was null / undefined? I've spent a couple of hours trying to find a solution to this, but to no avail.

In my case I have about 3 variables which get injected and all of them can be undefined since the user fills inn the data step by step. It just needs slightly different formatting depending on which are defined and which are not. Seems like a massive headache to have to evaluate all of the combinations and then as well define them in the lang files.

1 Answers1

1

Yes, the "straight" approach would be to have separate Texts.

"Hello!" is a different text than "Hello, Eric!".

Also, imagine in some other languages there might even be different words for a "Hello ..." followed by a name, and a stand-alone "Hello" with no name.

You could extract e.g. a <Greeting /> component, including the conditions, or it might be easier in this case to use the imperative API intl.formatMessage, again probably separating some parts of the code.

kca
  • 4,856
  • 1
  • 20
  • 41