3

I'm trying to add an extra class name to all the blocks by extending them. Documentation: Extending Blocks

I'm using blocks.BlockEdit to modify the edit component. I want to add a custom class name.

So far I have this

const withClass = createHigherOrderComponent( ( BlockListBlock ) => {
    return ( props ) => {
        let wrapperProps = props.wrapperProps;
        wrapperProps = {
            ...wrapperProps,
            className: 'my-custom-class',
        };

        return <BlockListBlock { ...props } wrapperProps={ wrapperProps } />;
    };
}, 'withClass' );

It's working by adding the custom class to the wrapper but it is overwriting the default block class. Is it possible to append to the current classes without overriding?

1

Yes, you can do this via the classnames() function.

import classnames from 'classnames';

const withClass = createHigherOrderComponent( ( BlockListBlock ) => {
    return ( props ) => {
        let wrapperProps = props.wrapperProps;
        wrapperProps = {
            ...wrapperProps,
            className={ classnames( 'my-custom-class', props.className ) }
        };

        return <BlockListBlock { ...props } wrapperProps={ wrapperProps } />;
    };
}, 'withClass' );
  • You don't need to use classnames() to do that, it's just a convenience (and overkill for this situation IMO). You could achieve the same thing with className={ 'my-custom-class ' + props.className } or className={ `my-custom-class ${props.className}` }. – Ian Dunn Apr 22 at 15:47
  • Good point Ian. You can do it either way. I guess it's down to personal preference really. I tend to use classnames because of my earliest experiences with the WordPress block editor when I thought you did have to do it that way so became a habit! – dgwyer Apr 25 at 11:37

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.