3

I have an app which uses React Intl and TypeScript.

I want to display a box with some info text, and I want it to be shown only if the text actually exists.

But I cannot do

<FormattedMessage id="my.id" />

because if my.id doesn't have a value, React Intl will fallback to the message id, i.e., my.id.

So what I tried to do was

const myId: string = 'myId';
const info: string = <FormattedMessage id={myId} />;
const infoExists: boolean = myId === info;

However, info is JSX.Element, not string.

Is there any way to do something like this?

Vegard Stikbakke
  • 749
  • 1
  • 7
  • 21

2 Answers2

2

For JS

const stringExists = !!this.props.intl.messages[id];

as answered here

Daya
  • 121
  • 1
  • 6
1

I figured it out.

const id: string = 'id';
const componentToBeRenderedIfIdHasValue = ...;

<FormattedMessage id={id}>
    {
        (message: string) =>
            message === id
            ? null
            : componentToBeRenderedIfIdHasValue
    }
</FormattedMessage>

I hope this can be of help to someone.

Vegard Stikbakke
  • 749
  • 1
  • 7
  • 21