Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 324
CyberJunkie Avatar asked Jan 07 '19 19:01

CyberJunkie


Video Answer


2 Answers

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] } />;
like image 157
Eugenio Valeiras Avatar answered Oct 19 '22 00:10

Eugenio Valeiras


If someName is an attribute, you can access it as

className={props.attributes.someName}
like image 2
Swopnil Dangol Avatar answered Oct 19 '22 00:10

Swopnil Dangol