5
votes

I'm using Gutenberg block filters to try and add a dynamic class name to the block’s wrapper component in the editor.

registerBlockType( name, {

    title: __( 'My Block' ),

    parent: [ 'myplugin/myblock' ],

    category: 'common',

    attributes: attributes,


    edit( { attributes, setAttributes, className } ) {      

        const { someName } = attributes;

        /* how can I pass someName from here to customClassName? */

        return (
            /* render something */
        );
    },

    save( { attributes } ) {

        const { someName } = attributes;

        /* how can I pass someName from here to customClassName? */

        return (
            /* render something */
        );
    },
});



const customClassName = createHigherOrderComponent( ( BlockListBlock ) => {
    return ( props ) => {
        return <BlockListBlock { ...props } className={ someName } />;
    };
}, 'customClassName' );

wp.hooks.addFilter( 'editor.BlockListBlock', 'myplugin/myblock', customClassName );

The issue: someName in constant customClassName is undefined.

How can I pass someName from the edit or save function to the constant customClassName? Which will be used in wp.hooks.addFilter.

Note: I can't add wp.hooks.addFilter or customClassName directly in the edit or save function. It will cause repeating.

3
Not sure what you mean by this, Can you clarify please? - Kousic
Ok I revised the question - CyberJunkie
What is the purpose of customClassName component? Is it just to add someName class or is there more? - maazadeeb
@MaazSyedAdeeb to add a class name which will be dynamic - CyberJunkie
Will the class name be someName or will it do some extra logic on top of it? I'm asking because as it stands, the custom filter seems somewhat redundant. - maazadeeb

3 Answers

3
votes

Simple Typo here :)

return <BlockListBlock className={ props.someName } { ...props } />;

NOTE: I would like to make props able to override the className if needed.

Another solution:

return <BlockListBlock { ...props } className={ [props.someName, props.className] } />;
2
votes

If someName is an attribute, you can access it as

className={props.attributes.someName}
1
votes

Actually, I guess you make a mistake in your question. surely, the someName value exists in attributes object and it is part of props object, so you can access it as simple as below:

const customClassName = createHigherOrderComponent(( BlockListBlock ) => {
  return ( props ) => {
    return <BlockListBlock {...props} className={props.attributes.someName} />;
  };
}, 'customClassName');

And another thing I want to say is that doesn't need curly braces and return functions for your code:

const customClassName = createHigherOrderComponent(
  BlockListBlock => props => (
    <BlockListBlock {...props} className={props.attributes.someName} />
  ),
  'customClassName'
);