Search code examples
wordpresswordpress-gutenberg

Change the tag in the return section in wordpress gutenburg block by condition


I want to change the tag in a save section using if condition.

I have created the block and return like this

return <a className={`card-item ` + className} href={cta_link} style={{backgroundColor: panel_colour}}>
------------
----
</a>

Now i want to change the anchor tag "" to "" by if condition. like

if ( cta_link )
<a className={`card-item ` + className} href={cta_link} style={{backgroundColor: panel_colour}}>
else
<div className={`card-item ` + className} style={{backgroundColor: panel_colour}}>

and also the closing tag. so is there any best way to do that ? i am new in the gutenburg block. Please let me know to enhance my knowledge.

Thank you


Solution

  • I use this pattern a lot when I have a block with an optional link:

    save: ( { attributes } ) => {
        const { url } = attributes;
    
        // If this block has a url, make it a link, otherwise make it a div.
        const Component = url !== '' ? 'a' : 'div';
        
        return (
            <Component></Component>
        );
    }