Search code examples
reactjstypescriptionic-frameworktsx

How to conditionally render a prop in TSX


I am trying to do the following in a functional component using TypeScript (I abstracted it a bit):

return <IonToast {canClose && button={close}} 

It isn't allowed to wrap a prop inside a conditional. But what would be the best solution to have such logic?

I though about assigning the 'close' variable before the return, but since Ionic is an external component library, it doesn't accept an empty variable.

The IonToast is typed in node-modules with the following. So it doesn't like it if you pass anything but a valid value.

export interface ToastOptions {
    buttons?: (ToastButton | string)[];
}

The ts error goes like this

Types of property 'button' are incompatible.     Type 'string | boolean | undefined' is not assignable to type 'string | undefined'.       Type 'false' is not assignable to type 'string | undefined'.

Solution

  • UPDATED

    According to this document

    You can have this logic for your buttons attribute

    const buttons: ToastButton[] = canClose ? [close] : [] //`close` needs to be `ToastButton` type
    return <IonToast buttons={buttons} /> 
    

    OLD ANSWER

    I don't know which is the best solution for this case, but I'm personally using this way

    return <IonToast button={canClose ? close : () =>{}} /> 
    

    The second param is an empty function that would help to prevent errors, just in case you call button() (indirect to close()) in IonToast component.