Search code examples
reactjswordpress-gutenberg

Gutenberg/React pass dynamic property to filter function


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.


Solution

  • If someName is an attribute, you can access it as

    className={props.attributes.someName}