< Back to Coding, React

How to conditionally wrap an element in React

const ConditionalWrapper:any = ({condition, wrapper, children}:any) => 
condition ? wrap(children) : children;

<ConditionalWrapper condition={element.url} 
                 wrapper={(children:any) => <a href={element.url} target="_blank" rel="noreferrer">{children}</a>}>
      /* children content inside your link */

The ConditionalWrap component checks the condition (in this example the element.url) and if it exists put the wrapper around the children, otherwise just render the children. The wrapper in this example is a link. You can put whatever content you want where the comment is to be put inside the link.

Leave a Reply

Your email address will not be published. Required fields are marked *