0

I am trying & learning to build custom block/template for Gutenberg and would like to "pre-set" CSS class for some specific block. Is it possible to add it like below?

Refer: [Template and Block][1]

For example, defined CSS class for one of the heading blockHeadStyle:

function myplugin_register_book_post_type() {
    $args = array(
        'public' => true,
        'label'  => 'Books',
        'show_in_rest' => true,
        'template' => array(
            array( 'core/image', array(
                'align' => 'left',
            ) ),
            array( 'core/heading', array(
                'placeholder' => 'Add Author...',
                'class' => 'blockHeadStyle'
            ) ),
            array( 'core/paragraph', array(
                'placeholder' => 'Add Description...',
            )),
        ),
    );
    register_post_type('book', $args);
}
add_action('init', 'myplugin_register_book_post_type');
2

This can be done using the block filters API.

Here is an example of adding a class to the block in the editor.


const withClientIdClassName = createHigherOrderComponent( ( BlockListBlock ) => {
    return ( props ) => {
        const customClass = 'custom-classname' );
        return (
            <BlockListBlock { ...props } className={ customClass }/>
        );
    };
}, 'withClientIdClassName' );

addFilter( 'editor.BlockListBlock', 'my-plugin/with-client-id-class-name', withClientIdClassName );

The above code will add the custom-classname class to each block in the list of block in the editor.

If you're looking to only affect a specific block, props has name property that can be checked:


const withClientIdClassName = createHigherOrderComponent( ( BlockListBlock ) => {
    return ( props ) => {
        if( 'core/heading' === props.name ) {
            const customClass = 'custom-classname' );
            return (
                <BlockListBlock { ...props } className={ customClass }/>
            );
        } else {
             <BlockListBlock { ...props }/> 
        }
    };
}, 'withClientIdClassName' );

addFilter( 'editor.BlockListBlock', 'my-plugin/with-client-id-class-name', withClientIdClassName );

Hope this helps!

  • Thank you very much, will try on it! – kevinckc Apr 29 at 15:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.