Search code examples
typescriptreact-intl

Checking if a message is empty with React Intl and Typescript


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?


Solution

  • 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.