Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading