I’ve been reviewing tutorials on creating blocks for Gutenberg but I am unclear how to handle a particular use case – conditional blocks.

I am looking at creating a custom post type for which I will register my own block type. These blocks will only be displayed if certain conditions are true. These conditions will be either boolean flags or integer comparisons (the values coming from wither custom user variables (meta) or session values).

If all conditions are true the block should be rendered but if one or more are false then (obviously) nothing is shown.

I cannot quite get my head around where I would place the logic for this. Admittedly my grasp of this new Gutenberg system is a bit shaky which is probably why I need some assistance.

For example:

<p logic="IF(is_logged_in,SHOW,HIDE)">My wonderful secret bit just for members.</p>

3 s
3

In the edit method for your custom block, when rendering the components you can use the “conditional + &&” pattern:

    <PanelBody title={ __( 'My Panel' ) } >

        { myCustomBool &&
            <MyComponent
                value={theValue}
                onChange={ value => {
                    myChangeCallback(value);
                } }
            />
        }
        { 'marmots' !== myCustomThing &&
            <MyOtherComponent
                value={theValue}
                onChange={ value => {
                    myOtherCallback(value);
                } }
            />
        }

    </PanelBody>

In the above example, the conditionals just before the “&&” will determine whether the component that follows will be rendered.

This is sometimes referred to as a “short circuit conditional”.

Leave a Reply

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